SQL COUNT(*) return 0 IFNULL with WHERE 子句和 GROUP_BY on same table
SQL COUNT(*) return 0 IFNULL with WHERE clauses and GROUP_BY on same table
即使计数为 null
,结果也应该 return 包含日期的一行。
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
LEFT JOIN
是正确的,但是 table 你所做的 Left join
。您需要 calendar
table 和 List dates
当没有找到特定 date
的记录时,您不必使用 IFNULL
,然后 Count
聚合将 return 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
table他是一篇文章:Calendar Tables: An Invaluable Database Tool
即使计数为 null
,结果也应该 return 包含日期的一行。
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
LEFT JOIN
是正确的,但是 table 你所做的 Left join
。您需要 calendar
table 和 List dates
当没有找到特定 date
的记录时,您不必使用 IFNULL
,然后 Count
聚合将 return 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
table他是一篇文章:Calendar Tables: An Invaluable Database Tool