零匹配显示在组中

时间:2012-03-08 02:43:04

标签: mysql database query-optimization

查询

SELECT 
   c.class_id,
   count(s.student_id) as total_students 
FROM 
   classes c
   LEFT JOIN students s ON c.class_id = s.class_id
GROUP BY c.class_id;

预期结果

445 15
448 19
451  9
455 0
478 0
489 0
501 84

但这是上述查询的结果

445 15
448 19
451  9
455 0
501 84

如果我通过where子句压缩id:455,它将478显示为0.不知何故,它的分组超过零..

PS:它是深夜,我的大脑是油炸的

----编辑--- 下面的解决方案有效,但这不起作用:(添加了过滤学生的条件)。此查询消除了所有0的

SELECT c.class_id,
       SUM
       (
        CASE
         WHEN s.student_id IS NULL THEN 0
         ELSE 1
        END
       ) as total_students 
  FROM classes c LEFT JOIN students s ON c.class_id = s.class_id WHERE s.student_type='instate'
GROUP BY c.class_id;

2 个答案:

答案 0 :(得分:1)

我想s.student_id聚合函数中的COUNT值的NULL值可能是原因。

尝试使用此版本(SUM聚合CASE语句):

SELECT c.class_id,
       SUM
       (
        CASE
         WHEN s.student_id IS NULL THEN 0
         ELSE 1
        END
       ) as total_students 
  FROM classes c LEFT JOIN students s ON c.class_id = s.class_id
GROUP BY c.class_id;

答案 1 :(得分:0)

它会计算每个班级的学生,然后left join他们(left选择所有班级,不仅仅是那些有学生的班级)。对于那些coalesce返回0 s的学生,left join会向没有学生的课程返回null

select c.class_id, coalesce(s.total_students, 0) as total_students
from classes c
left join (
    select class_id, count(student_id) as total_students
    from students
    where student_type='instate'
    group by class_id
) s on c.class_id = s.class_id
相关问题