MySQL已知两个时间点,求它们之间的日期列表

数据库 投稿 43600 0 评论

MySQL已知两个时间点,求它们之间的日期列表

在业务表需要得到缺失的日期,这个时候就需要Mysql查询两个日期(时间点)之间的日期列表。

通过创建临时表实现:

select * from
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
 (select 0 i 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 i 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) t1,
 (select 0 i 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) t2,
 (select 0 i 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) t3,
 (select 0 i 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) t4) v
where selected_date between '2021-02-25' and '2021-03-05';
+---------------+
| selected_date |
+---------------+
| 2021-02-25    |
| 2021-02-26    |
| 2021-02-27    |
| 2021-02-28    |
| 2021-03-01    |
| 2021-03-02    |
| 2021-03-03    |
| 2021-03-04    |
| 2021-03-05    |
+---------------+
9 rows in set (0.094 sec)

通过存储过程实现:

DELIMITER $$
 
DROP PROCEDURE IF EXISTS DayRangeProc$$
 
CREATE PROCEDURE DayRangeProc(IN start_date datetime , IN end_date datetime )
      BEGIN
              DECLARE temp  INT;
              DECLARE range_day  INT;
 
              SET temp = 0;
              SET range_day = (SELECT DATEDIFF(end_date,start_date));
 
              WHILE temp  <= range_day DO
                    select ADDDATE(start_date, temp);
                    SET temp = temp + 1;
              END WHILE;
      END$$
 
  DELIMITER ;
 
Call DayRangeProc('2020-9-1','2020-9-10');

编程笔记 » MySQL已知两个时间点,求它们之间的日期列表

赞同 (95) or 分享 (0)
游客 发表我的评论   换个身份
取消评论

表情
(0)个小伙伴在吐槽