简体   繁体   English

在MySQL中使用GROUP BY在COUNT中包含零

[英]Include zero in COUNT with GROUP BY in MySQL

I'm looking to make a query in MySQL to list all the faculties and their number of students given the following table structure: 我希望在MySQL中进行查询,列出所有学院及其学生人数,并给出以下表格结构:

mysql表

My query looks like: 我的查询如下:

SELECT `f`.`id`, `f`.`name`, COUNT(*) `total`
FROM `student` `s`
INNER JOIN `course` `c` ON `c`.`id` = `s`.`course_id`
LEFT JOIN `faculty` `f` ON `f`.`id` = `c`.`faculty_id`
GROUP BY `c`.`faculty_id`
ORDER BY `f`.`name`

And I'm getting this result: 我得到了这个结果:

查询结果

but I need to get all the faculties, even the ones without registered students. 但是我需要得到所有的院系,甚至是那些没有注册学生的院系。

If I use a LEFT JOIN with the course table I get the same results. 如果我在course表中使用LEFT JOIN,我会得到相同的结果。

If you want all the faculties; 如果你想要所有的院系; your starting table for the JOIN should be the faculty table. 你的JOIN起始表应该是教师表。 Then do Left joins on the other table accordingly. 然后相应地在另一个表上执行Left连接。

Use the following query: 使用以下查询:

SELECT `f`.`id`, `f`.`name`, COUNT(`s`.`id`) AS `total`
FROM `faculty` AS `f` 
LEFT JOIN `course` AS `c` ON `f`.`id` = `c`.`faculty_id` 
LEFT JOIN `student` AS `s` ON `c`.`id` = `s`.`course_id` 
GROUP BY `f`.`id`, `f`.`name` 
ORDER BY `f`.`name`

You need to revese the query, your primary tables is faculties (or use right join) : important - since you want to count cases of zero students you need to treat NULL values that might come up, joining the students table: 你需要尊重查询,你的主要表是院系(或使用正确的联接): 重要 - 因为你想要计算学生的案例,你需要处理可能出现的NULL值,加入学生表:

SELECT
`f`.`id`, `f`.`name`, SUM(IF(s.id IS NULL, 0,1) `total`
FROM
faculty f
LEFT JOIN course c ON `f`.`id` = `c`.`faculty_id`
LEFT JOIN student s ON `c`.`id` = `s`.`course_id`
GROUP BY `c`.`faculty_id` ORDER BY `f`.`name`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM