Mysql
 sql >> Database >  >> RDS >> Mysql

Restituisce NULL se Count(*) è zero

Innanzitutto, ti manca un GROUP BY clausola in fondo alla query per raggruppare per 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

Quindi, se vuoi semplicemente non mostrare le righe in cui total_student =0, puoi utilizzare la clausola 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

Oppure puoi cambiare LEFT JOIN a INNER JOIN fare la stessa cosa in questo caso.

Infine, se invece vuoi sostituire 0 con null ma hai ancora righe, puoi aggiornare l'istruzione select portando i totali a:

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