给定一个开始日期和结束日期,写个sql把中间的每天都查出来(包括开始和结束日期)。
给定开始时间是2023-03-12,结束时间是2023-03-22,sql如下:
SELECT DATE_ADD('2023-03-12', INTERVAL seq DAY) AS `day`
FROM (
SELECT 0 seq UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL
SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9 UNION ALL SELECT 10
) t
WHERE DATE_ADD('2023-03-12', INTERVAL seq DAY) <= '2023-03-22'
查询结果
day
2023-03-12
2023-03-13
2023-03-14
2023-03-15
2023-03-16
2023-03-17
2023-03-18
2023-03-19
2023-03-20
2023-03-21
2023-03-22
如果要动态处理,可以使用mybatis的foreach标签处理该sql
参数dateStart、dateEnd、numList分别代表开始时间、结束时间、差值数集合
SELECT DATE_ADD(DATE_FORMAT(#{dateStart},'%Y-%m-%d'), INTERVAL seq DAY) AS `day`
FROM (
SELECT 0 seq UNION ALL
<foreach collection="numList" item="numItem" separator=" UNION ALL " open=" " close=" ">
SELECT #{numItem}
</foreach>
)
WHERE DATE_ADD(DATE_FORMAT(#{dateStart},'%Y-%m-%d'), INTERVAL seq DAY) <= DATE_FORMAT(#{dateEnd},'%Y-%m-%d')