我的桌子
课堂
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
最佳答案
您需要一个整数源来进行联接。如果您有足够的行,则可以使用相同的表和变量:
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