右连接不起作用

时间:2012-07-27 07:46:36

标签: mysql join

SELECT
  Student.id,
  Student.first_name,
  Student.last_name, 
  count(`Attendance`.`id`) as total 
FROM `karate`.`attendances` AS `Attendance` 
RIGHT JOIN `karate`.`students` AS `Student` ON (`Attendance`.`student_id` = `Student`.`id`)
WHERE 1
  AND `Attendance`.`attendance_date` BETWEEN '2012-07-01' AND '2012-07-31' 
  AND (Student.active = '1') 
  AND (Student.type = 'student') 
GROUP BY `Student`.`id` 
ORDER BY total ASC

我希望所有学生的记录都包含在给定日期范围内的总就诊人数,但它只显示那些有出勤率的学生的两个记录。 但 如果我们删除日期检查条件,它工作正常。

提前致谢

1 个答案:

答案 0 :(得分:0)

这是因为右边连接的行attendance_date的值为NULL。您需要在您的条件中包含此案例:

WHERE 1
  AND (`Attendance`.`attendance_date` IS NULL
         OR `Attendance`.`attendance_date` BETWEEN '2012-07-01' AND '2012-07-31')
  AND (Student.active = '1') 
  AND (Student.type = 'student')