我在问题和分数之间存在一对多的关系。我的表设置是:
Table Question: id int auto_increment primary key, question varchar(255); Table Score: id int auto_increment primary key, score float, question_id int foreign key
对于每个问题,我想找到平均分数,因此我需要question从“问题”表中计算平均值。
question
我试过了:
SELECT Question.question, SUM(Score.score)/COUNT(Score.question_id) FROM `Question` INNER JOIN `Score` WHERE Question.id = Score.question_id;
但这只是返回第一个问题和平均值。您可以在我的SQLFiddle链接中看到它的运行情况。
我需要修改什么才能返回所有问题及其平均分数?
您忘记添加GROUP BY条款,
GROUP BY
SELECT ... FROM... GROUP BY Question.question
您也可以选择使用 AVG()
AVG()
SELECT Question.question, AVG(Score.score) AS average FROM Question INNER JOIN Score ON Question.id = Score.question_id GROUP BY Question.question