Mysql
 sql >> Base de données >  >> RDS >> Mysql

MySql count() pour renvoyer 0 si aucun enregistrement trouvé

Il n'y a pas d'enregistrement pour le mois de January c'est pourquoi vous n'obtenez aucun résultat. Une solution qui fonctionne consiste à joindre une sous-requête contenant la liste des mois que vous souhaitez afficher sur la liste.

SELECT count(b.id) as totalRec
FROM   (
            SELECT 'January' mnth
            UNION ALL
            SELECT 'February' mnth
            UNION ALL
            SELECT 'March' mnth
        ) a
        LEFT JOIN post b
            ON a.mnth = DATE_FORMAT(b.date, '%M') AND
               year(b.date) =  '2013' AND 
               DATE_FORMAT(b.date, '%M') IN ('January', 'February', 'March') 
GROUP  BY year(b.date)-month(b.date) 
ORDER  BY b.date ASC

SORTIE

╔══════════╗
║ TOTALREC ║
╠══════════╣
║        0 ║
║        7 ║
║        9 ║
╚══════════╝