【问题标题】:MySQL how to show rows that also does not match where clauseMySQL如何显示也不匹配where子句的行
【发布时间】:2016-04-30 22:35:32
【问题描述】:

我有这个问题:

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' 以及尚未设置日期的所有行。换句话说,我想显示班级中的所有学生,如果尚未为这些学生设置日期,它将显示为空。 这就是我想要的:http://i.imgur.com/jmsuSF5.png

因此,总而言之,我需要显示满足子句的行以及日期为空或尚不存在的行。 我该如何编写这个查询?

【问题讨论】:

  • 为什么这个标签是sql-server
  • 您可以只为日期设置一个默认值,并通过添加OR进行检查

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


【解决方案1】:

尝试将与连接表相关的条件从查询末尾移动到每个连接的表各自的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

【讨论】:

  • 谢谢@Asaph,效果很好。正是我需要的。再次感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-28
  • 1970-01-01
  • 2013-03-20
  • 1970-01-01
  • 2018-08-25
  • 2015-09-17
相关资源
最近更新 更多