标签:ima 方便 rom mat select -- 分段 sts sele
为了解决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;
标签:ima 方便 rom mat select -- 分段 sts sele
原文地址:https://www.cnblogs.com/lancelee98/p/10006710.html