Problem constructing where clause to include null/0 values
I have an application where users can take tests (which are composed of questions and answers).
I'm trying to construct a query that returns a count of answers grouped by question, for a specific teacher and test. The problem is I would like the query to return 0 count for questions with no answers.
answers
- id
- question_id
- test_id
- student_id
questions
- id
teacher_students
- student_id
- teacher_id
tests
- id
Query
SELECT COUNT(answers.id) AS rcount,
questions.id
FROM "questions"
LEFT JOIN answers ON answers.question_id = questions.id
LE开发者_开发知识库FT 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
Output
rcount | question_id
--------+----
4 | 1
2 | 3
Desired Output
rcount | question_id
--------+----
4 | 1
0 | 2
2 | 3
0 | 4
If I remove teacher_students.teacher_id = 1
, the number of questions returned is correct, but the count is not.
Move the teacher_students.teacher_id = 1
check from the WHERE
clause to the joining ON
clause.
When a condition that refers to a table in the right side of a LEFT JOIN
is put in the WHERE clause, the LEFT JOIN is cancelled and it acts as an 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
精彩评论