MySQL Select 两列之间的范围日期,不使用 table 列
MySQL Select range date between two columns without using table columns
在我的 sql 中,我想在不使用 table 列的情况下获取两个日期之间的日期差异
例如
SELECT BETWEEN '2012-01-10' AND '2012-01-15' as date1;
我必须得到以下日期作为输出
'2012-01-11'
'2012-01-12'
'2012-01-13'
'2012-01-14'
如何编写查询以获得如上的输出
如果你是运行MySQL8.0,你可以用递归查询来实现:
with recursive cte as (
select '2012-01-10' + interval 1 day as dt
union all
select dt + interval 1 day from cte where dt + interval 1 day < '2012-01-15'
)
select * from cte
这会在作为输入给出的界限之间为每个日期生成一行。
WITH RECURSIVE
cte AS ( SELECT @startdate + INTERVAL 1 DAY `date`
UNION ALL
SELECT `date`+ INTERVAL 1 DAY
FROM cte
WHERE `date` < @enddate - INTERVAL 1 DAY )
SELECT *
FROM cte
MySQL 8+ 需要。
my sql version used 5.6
maximum 1 year
SELECT @startdate + INTERVAL (n3.num * 7 * 7 + n2.num * 7 + n1.num + 1) DAY `date`
FROM ( SELECT 0 num union select 1 union select 2 union select 3
union select 4 union select 5 union select 6) n1
JOIN ( SELECT 0 num union select 1 union select 2 union select 3
union select 4 union select 5 union select 6) n2
JOIN ( SELECT 0 num union select 1 union select 2 union select 3
union select 4 union select 5 union select 6 union select 7) n3
HAVING `date` < @enddate;
最大。经期长度为 7 * 7 * 8 = 392 天。
在我的 sql 中,我想在不使用 table 列的情况下获取两个日期之间的日期差异 例如
SELECT BETWEEN '2012-01-10' AND '2012-01-15' as date1;
我必须得到以下日期作为输出 '2012-01-11' '2012-01-12' '2012-01-13' '2012-01-14'
如何编写查询以获得如上的输出
如果你是运行MySQL8.0,你可以用递归查询来实现:
with recursive cte as (
select '2012-01-10' + interval 1 day as dt
union all
select dt + interval 1 day from cte where dt + interval 1 day < '2012-01-15'
)
select * from cte
这会在作为输入给出的界限之间为每个日期生成一行。
WITH RECURSIVE
cte AS ( SELECT @startdate + INTERVAL 1 DAY `date`
UNION ALL
SELECT `date`+ INTERVAL 1 DAY
FROM cte
WHERE `date` < @enddate - INTERVAL 1 DAY )
SELECT *
FROM cte
MySQL 8+ 需要。
my sql version used 5.6
maximum 1 year
SELECT @startdate + INTERVAL (n3.num * 7 * 7 + n2.num * 7 + n1.num + 1) DAY `date`
FROM ( SELECT 0 num union select 1 union select 2 union select 3
union select 4 union select 5 union select 6) n1
JOIN ( SELECT 0 num union select 1 union select 2 union select 3
union select 4 union select 5 union select 6) n2
JOIN ( SELECT 0 num union select 1 union select 2 union select 3
union select 4 union select 5 union select 6 union select 7) n3
HAVING `date` < @enddate;
最大。经期长度为 7 * 7 * 8 = 392 天。