0

即使计数为 ,结果也应返回带有日期的行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 JOINand 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

4

1 回答 1

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表,他是一篇文章:日历表:一个无价的数据库工具

于 2016-10-11T16:29:25.367 回答