Mysql加入并计算每个类别

时间:2017-05-10 04:32:49

标签: join mysqli count

嗨,我有这样的桌子 的考试

id | exam_name
1  | computer science
2  | Environment science

exam_students

id | exam_id | student_name
1  | 1       | Josh
2  | 1       | Michael
3  | 1       | John

我只需要加入并统计每个考试的学生总数并输出类似的内容

exam_name          | total_students |
computer science   | 3              |
Environment science| 0              |

感谢您的任何帮助和建议

1 个答案:

答案 0 :(得分:1)

试试这个

SELECT
    a.exam_name, count(b.id) AS total_students
FROM
    exams a
LEFT JOIN exam_students b ON a.id = b.exam_id
GROUP BY
    a.id

希望这个帮助