SQL查询LEFT JOIN问题(MySQL)
我有 2 个表
SCHOOLS
(ID、SCHOOL_NAME、CITY_ID)学生
(ID、STUDENT_NAME、SCHOOL_ID)。
我想列出特定城市的学校以及学生人数(学校名称|学生人数)
一种方法是使用相关子查询 -
select sh.school_name,
(select count(*)
from student
where school_id = sh.id) as student_count
from schools sh
where sh.city_id = 1
但由于不建议使用相关查询,我想避免这种情况;我尝试了分组方式 -
select sh.school_name,
count(st.school_id) as student_count
from schools sh
left join students st on sh.id = st.school_id
where sh.city_id = 1
group by st.school_id
现在,只有当学校的学生人数 > 时,这才有效。 0.所以我猜测左连接概念不起作用,这意味着如果任何没有学生的学校应该被列为student_count = 0,但这种情况没有发生。有趣的是 - 我确实看到了 Student_count = 0 的“一条”记录,但仅此而已。
我的 LEFT JOIN 查询有什么问题吗?
I have 2 tables
SCHOOLS
(ID, SCHOOL_NAME, CITY_ID)STUDENTS
(ID, STUDENT_NAME, SCHOOL_ID).
I want to list schools in a particular city along with the student count (School Name| Student Count)
One way to do this is to have co-related subquery -
select sh.school_name,
(select count(*)
from student
where school_id = sh.id) as student_count
from schools sh
where sh.city_id = 1
But since co-related queries are not recommended, I want to avoid that & I tried a group by -
select sh.school_name,
count(st.school_id) as student_count
from schools sh
left join students st on sh.id = st.school_id
where sh.city_id = 1
group by st.school_id
Now this works only if the student count for a school is > 0. So i m guessing the left join concept is not working, meaning if any schools that has no students should be listed as student_count=0, but that is not happening. The interesting thing is - i do see "one" record with student_count = 0, but thats about it.
Anything wrong in my LEFT JOIN query??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
用途:
由于使用 LEFT JOIN,如果没有与学校关联的学生,则对
st
的引用将为 NULL。 COUNT 不计算 NULL 值,因此如果没有关联的学生,则student_count
将为零。Use:
Because of using the LEFT JOIN, references to
st
will be NULL if there are no students associated with the school. COUNT doesn't count NULL values, so if there are no students associated thenstudent_count
will be zero.尝试按 sh.id 而不是 st.school_id 分组
Try grouping by sh.id instead of st.school_id