mysql生成日期的辅助表,为了解决mysql按日期分组查询统计的时候,没有数据补0

CREATE TABLE num ( i INT );
-- 创建一个表用来储存0-9的数字
INSERT INTO num ( i )
VALUES
    ( 0 ),
    ( 1 ),
    ( 2 ),
    ( 3 ),
    ( 4 ),
    ( 5 ),
    ( 6 ),
    ( 7 ),
    ( 8 ),
    ( 9 );
    
-- --------------------------------------------------------------

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;

 

转载地址:https://www.cnblogs.com/lancelee98/p/10006710.html?tdsourcetag=s_pctim_aiomsg

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值