在查询结果

时间:2015-05-07 01:24:45

标签: mysql sql

我有一个非常简单的查询:http://pastebin.com/CGPZM14U

它会计算特定年份每月的文章数量。让我们假设我在2014年8月没有写任何内容。显而易见,而不是8月= 0我将在7月之后接下来的9月。

如何添加计数等于0的缺失月份。我有一些工作示例,但我正在寻找尽可能简单干净的解决方案。

2 个答案:

答案 0 :(得分:0)

创建一个包含所有月份的表格,然后将其与您的查询一起加入。

select count(1) as count, months.month, year(published_at) as year
from months left join articles on months.month = month(published_at)
where published_at >= (now() - interval 1 year) and published_at <= now()
group by month(published_at)
order by year asc, month asc

它会起作用,但会从1月到12月返回结果,并且不会给你几年。之前有一个类似的问题,然后我想出了一个非常复杂的查询,所以如果你没有找到更简单的东西,请考虑看看:

Between dates query not working, now we're in a new year

答案 1 :(得分:-1)

Count替换为ISNULL(Count, 0)