在資料庫管理中,可視化用戶群增長通常需要圖形表示。要建立這樣的圖表,您可能有一個收集特定日期範圍內每日使用者計數的查詢。但是,如果某些日子缺乏使用者活動,這些日期將從結果中省略。為了解決這個問題,我們來探討如何取得完整的日期範圍,包括零記錄的日期。
在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中文網其他相關文章!