在数据库管理中,可视化用户群增长通常需要图形表示。要创建这样的图表,您可能有一个收集特定日期范围内每日用户计数的查询。但是,如果某些日子缺乏用户活动,这些日期将从结果中省略。为了解决这个问题,我们来探讨如何获取完整的日期范围,包括零记录的日期。
在 MySQL 中,以下查询检索指定日期范围内按天分组的用户计数:
SELECT DATE(datecreated), count(*) AS number FROM users WHERE DATE(datecreated) > '2009-06-21' AND DATE(datecreated) <= DATE(NOW()) GROUP BY DATE(datecreated) ORDER BY datecreated ASC
虽然此查询提供了大部分所需信息,但它排除了零用户的日期。要包含空日期,我们可以利用以下方法:
SELECT * FROM ( SELECT date_add('2003-01-01 00:00:00.000', INTERVAL n5.num*10000+n4.num*1000+n3.num*100+n2.num*10+n1.num DAY ) as date FROM (SELECT 0 AS num UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) n1, (SELECT 0 AS num UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) n2, (SELECT 0 AS num UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) n3, (SELECT 0 AS num UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) n4, (SELECT 0 AS num UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) n5 ) a WHERE date > '2011-01-02 00:00:00.000' AND date < NOW() ORDER BY date
通过此查询,您可以生成指定范围内的日期序列并将它们包含在结果中,即使这些日期没有对应的日期记录在您的数据库中。
以上是如何在MySQL中检索某个范围内的所有日期,包括零记录的日期?的详细内容。更多信息请关注PHP中文网其他相关文章!