3

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

你能告诉我怎么做吗?

谢谢 :)

4

3 回答 3

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 JOININNER JOIN在这种情况下完成相同的事情。

最后,如果您想将 0 替换为 null 但仍有行,则可以更新 select 语句以获取总计:

SELECT IF(COUNT(student_name) = 0, NULL, COUNT(student_name)) AS total_student, school_name
于 2013-02-03T17:21:47.103 回答
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
于 2013-02-03T17:26:25.100 回答
0

请尝试使用 CASE 语法:http ://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html

于 2013-02-03T17:25:48.627 回答