MySQL如何显示也与where子句不匹配的行

时间:2016-01-24 17:01:50

标签: mysql sql sql-server database where-in

我有这个问题:

SELECT `y78f2_students`.`firstname` , `y78f2_students`.`lastName` , `y78f2_students`.`student_id`,`y78f2_attendance`.`is_present`, `y78f2_attendance`.`note`, `y78f2_attendance`.`thedate`  
FROM `y78f2_students`
INNER JOIN `y78f2_enrolls` ON `y78f2_enrolls`.`student_id` = `y78f2_students`.`student_id` 
INNER JOIN `y78f2_attendance` ON `y78f2_attendance`.`student_id` = `y78f2_students`.`student_id` 
WHERE `y78f2_enrolls`.`term` = 'Term 2 2016' 
AND `y78f2_enrolls`.`crn_class` = 'Math1R1' 
and `y78f2_attendance`.`thedate` = '2016-01-24'
ORDER BY thedate desc

此查询仅返回日期为2016-01-24'的行。目前只有一行:http://i.imgur.com/jRTBqQ0.png

我需要显示所有行term =' Term 2 2016'和crn_class` =' Math1R1'以及尚未设定日期的地方。为了说明我想要在课堂上显示所有学生,如果没有为这些学生设置日期,它将显示为null。 这就是我想要的:http://i.imgur.com/jmsuSF5.png

总而言之,我需要显示满足子句的行以及日期为null或尚未存在的行。 我该如何撰写此查询?

1 个答案:

答案 0 :(得分:3)

尝试从查询末尾移动与联接表相关的条件,直到每个联接的表的ON子句。此外,如果您要返回y78f2_attendance表中尚未存在任何行的记录,则该表应LEFT OUTER加入,而不是INNER加入。

SELECT `y78f2_students`.`firstname` , `y78f2_students`.`lastName`,
    `y78f2_students`.`student_id`,`y78f2_attendance`.`is_present`, 
    `y78f2_attendance`.`note`, `y78f2_attendance`.`thedate`  
FROM `y78f2_students`
INNER JOIN `y78f2_enrolls` ON
    `y78f2_enrolls`.`student_id` = `y78f2_students`.`student_id`
    AND `y78f2_enrolls`.`crn_class` = 'Math1R1'
LEFT OUTER JOIN `y78f2_attendance` ON
    `y78f2_attendance`.`student_id` = `y78f2_students`.`student_id`
    AND (`y78f2_attendance`.`thedate` IS NULL OR `y78f2_attendance`.`thedate` = '2016-01-24')
WHERE `y78f2_enrolls`.`term` = 'Term 2 2016' 
ORDER BY thedate desc