MySql count() to return 0 if no records found

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 ║
╚══════════╝

COALESCE is what you could use, if you have a table of dates and left joined against it. It goes left to right to return the first non null value. Your group by does look a little nutty at the minute, I have adjusted it.

SELECT
COALESCE(count(id),0) as totalRec
FROM ('post')
LEFT JOIN dates
ON dates.date = post.date
WHERE year(date) =  '2013'
AND monthname(date) IN ('January', 'February', 'March') 
GROUP BY month(date), year(date)
ORDER BY 'date' ASC

Where dates table is..

DATE
2013-01-01 
2013-01-02
2013-01-03
etc....

See here : http://easywebapps.blogspot.co.uk/2011/07/mysql-how-to-create-calendar-table.html

Tags:

Mysql

Sql