我的表
教室
id class no_of_seats start_seat_no end_seat_no
1 A1 3 105 107
2 A2 2 108 109
3 A3 2 110 111
我想在表格中插入数据 的 seat_records 像这样
id class seat_no
1 A1 105
2 A1 106
3 A1 107
4 A2 108
5 A2 109
6 A3 110
7 A3 111
8 A3 112
尝试做以前问题中给出的所有内容,但失败了。
SELECT 'A1' class, 105 start_seat_no, 107 end_seat_no
UNION ALL
SELECT 'A2',108,109
From classRoom
答案 0 :(得分:1)
您需要一个整数来源才能进行连接。如果您有足够的行,则可以使用相同的表和变量:
insert into seat_records(class, seat_no)
select class, cr.start_seat_no + n.n - 1
from ClassRoom cr join
(select @rn := @rn + 1 as n
from ClassRoom cross join
(select @rn := 0) vars
) n
on cr.start_seat_no + n.n - 1 <= cr.end_seat_no;
您应该将id
本身添加为自动递增列。这样,它将在输入时设置。如果你真的想在输入上设置它,你也可以使用变量:
insert into seat_records(id, class, seat_no)
select @id := @id + 1, class, cr.start_seat_no + n.n - 1
from ClassRoom cr join
(select @rn := @rn + 1 as n
from ClassRoom cross join
(select @rn := 0) vars
) n
on cr.start_seat_no + n.n - 1 <= cr.end_seat_no cross join
(select @id := 0) vars