mycosmos 2020-02-01
1、创建一个num表,用来存储数字0~9
CREATE TABLE num (i int);
2、在num表中生成0~9
INSERT INTO num (i) VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9);
3、生成一个存储日期的表,datalist是字段名
CREATE TABLE if not exists calendar(datelist date);
4、生成并插入日期数据
INSERT INTO calendar(datelist) SELECT adddate( ( -- 这里的起始日期,你可以换成当前日期 DATE_FORMAT("2016-1-1", ‘%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;
5、最后再添加主键即可
ALTER TABLE `calendar` ADD COLUMN `id` int UNSIGNED NOT NULL AUTO_INCREMENT COMMENT ‘主键‘ FIRST , ADD PRIMARY KEY (`id`);
执行sql生成从1900-01-01起的十万条数据
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 if not exists calendar(datelist date); -- 生成一个存储日期的表,datalist是字段名
-- 这里是生成并插入日期数据
INSERT INTO calendar(datelist) SELECT
adddate(
( -- 这里的起始日期,你可以换成当前日期
DATE_FORMAT("1900-1-1", ‘%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;
生成calendar表后,删除num的临时表。
————————————————
版权声明:本文为CSDN博主「Jonah_lxw」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/xiuwu0423/article/details/86672560