构造where子句以包含null / 0值的问题

时间:2011-06-29 21:41:35

标签: sql postgresql

我有一个应用程序,用户可以在其中进行测试(由问题和答案组成)。

我正在尝试构建一个查询,该查询返回按问题分组的答案计数,针对特定教师和测试。 问题是我希望查询返回0计数没有答案的问题。

答案

  • ID
  • question_id
  • 为test_id
  • student_id数据

问题

  • ID

teacher_students

  • student_id数据
  • teacher_id

测试

  • ID

查询

   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,则返回的问题数量是正确的,但计数不是。

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