[英]Return NULL if Count(*) is zero
I have the following mysql query: 我有以下mysql查询:
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'
It Returns: 它返回:
total_student school_name
0 NULL
What I am trying to achieve is, if total_student = 0 then show no value or NULL 我想要实现的是,如果total_student = 0则显示没有值或NULL
total_student school_name
Could you please tell me how to do it? 你能告诉我怎么做吗?
Thanks :) 谢谢 :)
First, you're missing a GROUP BY
clause at the bottom of your query to group by school_name
: 首先,您在查询底部缺少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
Then, if you want to simply not show rows where total_student = 0 then you can use the MySQL HAVING clause: 然后,如果您只想显示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
Or, you can change LEFT JOIN
to INNER JOIN
to accomplish the same thing in this case. 或者,您可以将LEFT JOIN
更改为INNER JOIN
以在此情况下完成相同的操作。
Finally, if instead you want to replace 0 with null but still have rows, you could update the select statement getting the totals to: 最后,如果你想用null替换0但仍然有行,你可以更新select语句,使总数达到:
SELECT IF(COUNT(student_name) = 0, NULL, COUNT(student_name)) AS total_student, school_name
Add a HAVING clause to filter out the 0 rows: 添加HAVING子句以过滤掉0行:
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'
HAVING total_student > 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.