SQL COUNT(*)在同一个表上返回0 IFNULL与WHERE子句和GROUP_BY

时间:2016-10-11 16:25:28

标签: mysql sql count sql-order-by ifnull

即使计数为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 JOINIFNULL,但我尝试了没有好结果。

期望的结果:

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

1 个答案:

答案 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