mysql生成连续时间段,间隔一个小时,从6点到22点
时间: 2023-07-18 14:29:51 浏览: 160
sql中时间以5分钟半个小时任意间隔分组的实现方法
您好!为了生成从6点到22点的连续时间段,间隔一个小时的MySQL查询语句如下:
```
SELECT DATE_FORMAT(date_add('2019-01-01 06:00:00', INTERVAL (t0+t1*10+t2*100+t3*1000+t4*10000+t5*100000) HOUR), '%Y-%m-%d %H:%i:%s') AS time_slot
FROM
(SELECT 0 AS t0 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) t0,
(SELECT 0 AS t1 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3) t1,
(SELECT 0 AS t2 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5) t2,
(SELECT 0 AS t3 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5) t3,
(SELECT 0 AS t4 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5) t4,
(SELECT 0 AS t5 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3) t5
WHERE date_add('2019-01-01 06:00:00', INTERVAL (t0+t1*10+t2*100+t3*1000+t4*10000+t5*100000) HOUR) <= '2019-01-01 22:00:00';
```
该查询语句使用了MySQL的日期格式化函数`DATE_FORMAT()`和日期计算函数`date_add()`,以及多表联查和条件判断语句。其中,`t0`至`t5`分别代表0~9的数字,通过多表联查生成0~999999的数字组合,再按照指定的时间间隔和起始时间计算每个时间段的具体时间。最后,通过条件判断筛选出符合要求的时间段并返回。
阅读全文