簡體   English   中英

如果Count(*)為零,則返回NULL

[英]Return NULL if Count(*) is zero

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

你能告訴我怎么做嗎?

謝謝 :)

首先,您在查詢底部缺少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以在此情況下完成相同的操作。

最后,如果你想用null替換0但仍然有行,你可以更新select語句,使總數達到:

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

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM