1. 程式人生 > >mysql生成日期的輔助表

mysql生成日期的輔助表

小時 cross hour 分段 add create value not sel

為了解決mysql按日期分組查詢統計的時候,沒有數據補0。可以生成連續的時間表格來輔助查詢
CREATE TABLE num (i int);-- 創建一個表用來儲存0-9的數字INSERT INTO num (i) VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9);-- 生成0-9的數字,方便以後計算時間

* 生成日期

CREATE TABLE num (i int);-- 創建一個表用來儲存0-9的數字
INSERT INTO num (i) VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9);

DROP TABLE calendar;
CREATE TABLE if not exists calendar(datelist date,datehour datetime);


INSERT INTO calendar(datelist) SELECT adddate( ( -- 這裏的起始日期,你可以換成當前日期 
DATE_FORMAT("2018-11-10", ‘%Y-%m-%d‘) ), numlist.id ) AS `date`
FROM 
( SELECT n1.i + n10.i * 10 + n100.i * 100 + n1000.i * 1000+ n10000.i * 10000 AS id 
FROM num n1 CROSS JOIN num AS n10 CROSS JOIN num AS n100 CROSS JOIN num AS n1000 CROSS JOIN num AS n10000 
) AS numlist; 

技術分享圖片

* 每一個小時為一個分段 生成如下輔助表

技術分享圖片

INSERT INTO calendar(datehour) 
SELECT 
DATE_ADD((DATE_FORMAT("2018-11-10", ‘%Y-%m-%d‘)),INTERVAL numlist.id HOUR) AS `date`
FROM ( 
SELECT n1.i + n10.i * 10 + n100.i * 100 + n1000.i * 1000+ n10000.i * 10000 AS id 
FROM num n1 
CROSS JOIN num AS n10 
CROSS JOIN num AS n100 
CROSS JOIN num AS n1000 
CROSS JOIN num AS n10000 ) AS numlist; 

 

mysql生成日期的輔助表