如何从另一个表中描述的时间段为每个日期向表中插入行?

时间:2017-06-06 21:39:16

标签: mysql

给定一个表alpha,具有以下结构:

id INT
period_start DATE
period_end DATE

表格beta

id INT
alpha_id INT
day DATE

对于表alpha中的每一行,我想在表beta中插入行,为beta.dayalpha.period_start之间的每个日期填充alpha.period_end

例如:

id | period_start | period_end
1  | 2017-01-01   | 2017-01-03

将被翻译成:

id | alpha_id | day
1  | 1        | 2017-01-01
2  | 1        | 2017-01-02
3  | 1        | 2017-01-03

想法?

1 个答案:

答案 0 :(得分:1)

这很有效,但效率很低。如果您确定周期不会超过一定的天数(下面的那个允许可笑的大周期:99999天,如果我没有记错的话),您可以调整它。

insert into beta(alpha_id, day)
select 
    a1.id, selected_date
from 
    alpha a1 join
    (select id, selected_date from 
        (select id, adddate(@period_start, 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,
            (select @period_start := min(period_start), @period_end := max(period_end) from alpha) init,
            (select id from alpha a3) id) v
    where selected_date <= @period_end) days on a1.id = days.id
where 
    selected_date between
        (select 
            period_start
        from 
            alpha a4
        where a1.id = a4.id) and
        (select 
            period_end
        from 
            alpha a5
        where a1.id = a5.id)

就个人而言,我会使用程序:更高效,更易读......总之,更优雅的imho。

无论如何,希望它有所帮助。

PS:我正在为beta表的id使用自动递增的字段。