首先,您在GROUP BY
查询底部缺少一个子句来分组school_name
:
SELECT count(student_name) AS total_student, school_name
FROM student
LEFT JOIN school_info ON school_info.school_id = student.school_id
WHERE student.status = '0'
GROUP BY school_name
然后,如果您只想不显示 total_student = 0 的行,那么您可以使用 MySQL HAVING 子句:
SELECT count(student_name) AS total_student, school_name
FROM student
LEFT JOIN school_info ON school_info.school_id = student.school_id
WHERE student.status = '0'
GROUP BY school_name
HAVING count(student_name) > 0
或者,您可以更改LEFT JOIN
为INNER JOIN
在这种情况下完成相同的事情。
最后,如果您想将 0 替换为 null 但仍有行,则可以更新 select 语句以获取总计:
SELECT IF(COUNT(student_name) = 0, NULL, COUNT(student_name)) AS total_student, school_name