即使计数为null
,结果也应返回包含日期的行。
SELECT DATE_FORMAT(created_date, '%Y-%m') AS date, COUNT(*) AS total
FROM mytable
WHERE created_date BETWEEN :startDate AND :endDate
AND condition = :condition
GROUP BY DATE_FORMAT(created_date, '%Y-%m')
ORDER BY created_date ASC
我看到我应该使用LEFT JOIN
和IFNULL
,但我尝试了没有好结果。
期望的结果:
array(1) {
[0]=> {
["date"]=>
string(7) "2016-01"
["total"]=>
string(1) "0"
}
[1]=> {
["date"]=>
string(7) "2016-02"
["total"]=>
string(4) "9492"
}
[2]=> {
["date"]=>
string(7) "2016-03"
["total"]=>
string(1) "0"
}
}
PS:我正在使用MySQL
答案 0 :(得分:0)
LEFT JOIN
是正确的,但您使用的是Left join
。您需要一个带有列表日期的calendar
表
如果找不到特定IFNULL
的记录,则您不必使用date
,然后Count
汇总将返回0
SELECT Date_format(c.dates, '%Y-%m') AS date,
Count(m.created_date) AS total
FROM Calendar_table c
LEFT JOIN mytable m
ON c.dates = Cast(m.created_date AS DATE)
WHERE created_date BETWEEN :startDate AND :endDate
AND condition = :condition
GROUP BY Date_format(c.dates, '%Y-%m')
ORDER BY c.dates ASC
为了创建calendar
表,他是一篇文章:Calendar Tables: An Invaluable Database Tool