如果Count(*)为零,则返回NULL

时间:2013-02-03 17:16:48

标签: mysql

我有以下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'

它返回:

total_student   school_name
  0               NULL

我想要实现的是,如果total_student = 0则显示没有值或NULL

total_student   school_name 

你能告诉我怎么做吗?

谢谢:)

3 个答案:

答案 0 :(得分:7)

首先,您在查询底部缺少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替换0但仍然有行,你可以更新select语句,使总数达到:

SELECT IF(COUNT(student_name) = 0, NULL, COUNT(student_name)) AS total_student, school_name

答案 1 :(得分:1)

添加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

答案 2 :(得分:0)