这个问题在这里已经有了答案:
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...
子句是导致这种行为的原因之一,如何使我的查询按我想要的方式工作?
1条答案
按热度按时间czfnxgou1#
试着用左连接代替右连接