按月份分组并返回结果为0的月份,按年度过滤

kkih6yb8  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(356)

这个问题在这里已经有了答案

mysql count不能显示0个值(1个答案)
两年前关门了。
我试图按月对给定表的结果进行分组并返回没有值的结果,我创建了另一个表,但我无法按年度筛选条目(例如, where YEAR(created) = 2018 ),但内部查询没有按预期返回月份。
我有这个问题。

SELECT 
    months.name as m, 
    count(MONTH(created_at)) as total 
from entries 
RIGHT JOIN months 
    ON MONTH(created_at) = months.id 
where YEAR(created_at) = 2018 
GROUP BY months.id

查询结果如下:

+----+------------------+---------------------------+
| id | month            | total                     |
+----+------------------+---------------------------+
|  1 | january          | 27                        |
|  3 | march            | 3                         |
|  5 | may              | 2                         |
+----+------------------+---------------------------+

我想实现以下目标:

+----+------------------+-------+
| id | month            | total |
+----+------------------+-------+
|  1 | january          | 27    |
|  2 | february         | 0     |
|  3 | march            | 3     |
|  4 | april            | 0     |
|  5 | may              | 2     |
|  6 | june             | 0     |
|  7 | july             | 0     |
|  8 | august           | 0     |
|  9 | september        | 0     |
| 10 | october          | 0     |
| 11 | november         | 0     |
| 12 | december         | 0     |
+----+------------------+-------+

我假设我的 where year... 子句是导致这种行为的原因之一,如何使我的查询按我想要的方式工作?

czfnxgou

czfnxgou1#

试着用左连接代替右连接

SELECT months.name as m, 
   IFNULL(Count(created_at), 0) as total 
  from months
  LEFT JOIN ENTRIES ON months.id = MONTH(created_at)
  where YEAR(created_at) = 2018 
  GROUP BY months.id

相关问题