我有这个SQL查询:
SELECT c.id as ID, c.class_name as CLASS, COUNT(e.student_id) AS STUDENT_COUNT
FROM classes as c
LEFT JOIN enrollments as e on e.class_id = c.id
where c.teacher_id = 8 AND e.approved = 1
group by c.class_name;
我尝试做的是获得所有课程和在这些课程中获得批准的学生人数。 sql查询应返回类似
的内容ID CLASS STUDENT_COUNT
1 Math 0
2 Biology 2
3 Algebra 1
4 Literature 5
问题是因为e.approved = 1我根本没有得到任何课程。建议?
我的架构如下
CLASSES表
id, teacher_id, class_name, grade
ENROLLMENTS表
id, class_id, student_id, approved
答案 0 :(得分:4)
更改您的查询以使用左连接条件中的e.approved:
SELECT c.id as ID, c.class_name as CLASS, COUNT(e.student_id) AS STUDENT_COUNT
FROM classes as c
LEFT JOIN enrollments as e on e.class_id = c.id
AND e.approved = 1
where c.teacher_id = 8
group by c.class_name;