MySql count() to return 0 if no records found

前端 未结 6 1508
太阳男子
太阳男子 2020-12-17 20:10

I have a set of posts on monthly basis. Now i need an array which contains total records of posts posted in each month. I tried below MySql query, Its working fine, but I wa

6条回答
  •  无人及你
    2020-12-17 20:56

    There is no record for the month of January that is why you are getting no result. One solution that works is by joining a subquery with contains list of months that you want to be shown on the list.

    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
    
    • SQLFiddle Demo

    OUTPUT

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

提交回复
热议问题