本文介绍了SQL-获取所有一对多关系的平均分数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在问题和分数之间存在一对多的关系.我的表格设置是:

I have a one-to-many relationship between Questions and Scores. My table setup is:

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,并且需要计算平均值.

For each question, I want to find the average score, so I need question from the Question table, and I need to calculate the average.

我尝试过:

SELECT Question.question, SUM(Score.score)/COUNT(Score.question_id) FROM `Question` INNER JOIN `Score` WHERE Question.id = Score.question_id;

但这只是返回第一个问题和平均值.您可以在我的SQLFiddle链接中看到它的运行情况.

But it's only returning the first question and average. You can see it in action at my SQLFiddle link.

我需要做些什么修改才能返回所有问题及其平均分数?

What do I need to modify for it to return all questions and their average scores?

推荐答案

您忘记添加GROUP BY子句,

SELECT ...
FROM...
GROUP BY Question.question

,您也可以选择使用AVG()

SELECT  Question.question, 
        AVG(Score.score) AS average  
FROM    Question INNER JOIN Score 
            ON Question.id = Score.question_id
GROUP   BY Question.question

  • SQLFiddle演示
    • SQLFiddle Demo
    • 这篇关于SQL-获取所有一对多关系的平均分数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 12:07