如何在Mysql语句中添加选择性行

时间:2018-09-12 22:30:55

标签: mysql sql procedure

我有一张桌子,上面有项目(A,B)和句点。我想添加包含每个项目缺少的时间段的行(对于项目A,添加具有周期1到4的行,对于项目B,添加具有周期3的行)。如果可能的话,在一个过程中或没有实际更改原始表(实际上我有1000多个项目)

原文:

item period
a    0
a    5
a    3
b    2
b    4

所需:

item period
a    0
a    1
a    2
a    3
a    4
a    5
b    2
b    3
b    4

谢谢

1 个答案:

答案 0 :(得分:0)

您需要一个数字表。让我假设您有一个:

select i.item, n.n as period
from (select item, min(period) as minp, max(period) as maxp
      from items
      group by item
     ) i join
     numbers n
     on n.n between i.minp and i.maxp;

如果没有这样的表,则可以生成一个表:

select i.item, n.n as period
from (select item, min(period) as minp, max(period) as maxp
      from items
      group by item
     ) i join
     (select (@rn := @rn + 1) as n
      from items i cross join
           (select @rn := -1) params
      limit 241
     ) n
     on n.n between i.minp and i.maxp;