我有一个应用程序,用户可以在其中进行测试(由问题和答案组成)。
我正在尝试构建一个查询,该查询返回按问题分组的答案计数,针对特定教师和测试。 问题是我希望查询返回0计数没有答案的问题。
SELECT COUNT(answers.id) AS rcount,
questions.id
FROM "questions"
LEFT JOIN answers ON answers.question_id = questions.id
LEFT JOIN teacher_students ON teacher_students.student_id = answers.student_id
WHERE (questions.test_id = 1)
AND (teacher_students.teacher_id = 1)
GROUP BY questions.id
ORDER BY questions.id
rcount | question_id
--------+----
4 | 1
2 | 3
所需输出
rcount | question_id
--------+----
4 | 1
0 | 2
2 | 3
0 | 4
如果我删除teacher_students.teacher_id = 1
,则返回的问题数量是正确的,但计数不是。
答案 0 :(得分:3)
将teacher_students.teacher_id = 1
子句从WHERE
子句移动到加入ON
子句。
当引用LEFT JOIN
右侧的表的条件放在WHERE子句中时,LEFT JOIN将被取消,并且它将充当INNER JOIN
。
SELECT count(teacher_students.student_id) AS rcount <--- changed
, questions.id
FROM "questions"
LEFT JOIN answers
ON answers.question_id = questions.id
LEFT JOIN teacher_students
ON teacher_students.student_id = answers.student_id
AND teacher_students.teacher_id = 1
WHERE questions.test_id = 1
GROUP BY questions.id
ORDER BY questions.id