MySQL GROUP BY date - 如何在没有行时返回结果
我正在编写一个查询来返回特定时间段内每天撰写的博客文章的数量。当某一天没有博客记录时,我的问题就出现了。通过我的查询,当天的结果完全被跳过。
这是我的查询:
SELECT DATE(`posted`), COUNT(`id`)
FROM `blogs` WHERE `status` = 'active'
&& `posted` BETWEEN `2011-01-01` AND `2011-05-01`
GROUP BY DATE(`posted`)
它返回类似于以下内容的内容:
count | date
_________________
2 | 2011-01-01
5 | 2011-01-02
1 | 2011-01-04
注意,它缺少 2011-01-03,因为它没有任何帖子。
我如何让它显示那些帖子数为 0 的日子?
I am writing a query to return the number of blog posts written per day over a certain period of time. My problem arises when there are no records of a blog for a given day. With my query, the result for that day is simply skipped altogether.
Here's my query:
SELECT DATE(`posted`), COUNT(`id`)
FROM `blogs` WHERE `status` = 'active'
&& `posted` BETWEEN `2011-01-01` AND `2011-05-01`
GROUP BY DATE(`posted`)
It returns something similar to:
count | date
_________________
2 | 2011-01-01
5 | 2011-01-02
1 | 2011-01-04
Notice that it is missing 2011-01-03 because it doesn't have any posts.
How do I get it to show those days with 0 posts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要有一个包含要查询的所有日期的表,并执行以下操作:
You'd need to have a table that contains all the dates you're going to query over, and do something along the lines of...
创建包含日期的表(取自 http://www .artfulsoftware.com/infotree/queries.php?&bw=1280#95):
To create the table containing the dates (taken from http://www.artfulsoftware.com/infotree/queries.php?&bw=1280#95) :