我在MySQL中有一个表,其中包含每个键的最小和最大日期值:
key | minDate | maxDate
1 2011-01-01 2011-01-10
2 2011-02-13 2011-02-15
3 2011-10-19 2011-12-10
如何为每个键的minDate和maxDate之间的每个日期创建一个包含一行的新表:
key | Date
1 2011-01-01
1 2011-01-02
... ...
1 2011-01-10
2 2011-02-13
2 2011-02-14
2 2011-02-15
3 2011-10-19
... ...
答案 0 :(得分:3)
使用integers table,您可以这样做:
SELECT "key", minDate + INTERVAL i DAY
FROM mytable
INNER JOIN integers
ON i <= DATEDIFF(maxDate, minDate)
假设“整数”表的列名为“i”,当然。
从那里,您可以使用INSERT INTO ... SELECT
填充新表格。
答案 1 :(得分:0)
从记忆中,它可能是这样的:
create table #res (
key int,
Date datetime
)
declare @minD datetime, @maxD datetime
select @minD = min(minDate), @maxD = max(maxDate) from tablename
while @minD <= @maxD do
insert into #res
select key, @minD from tablename where @minD >= minDate and @minD <= maxDate
select @minD = dateadd(@minD, interval 1 day)
end while;
select key, Date from #res
drop table #res
答案 2 :(得分:0)
使用递归公用表表达式(需要mysql 8或mariadb 10.2+):
with recursive expanded_ranges as (
select id, mindate dt
from ranges
union all
select expanded_ranges.id, expanded_ranges.dt+interval 1 day
from expanded_ranges
join ranges on expanded_ranges.id=ranges.id and dt<maxdate
)
select * From expanded_ranges;