在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中文網其他相關文章!