我有一张类似于此的表格:
id
name
datetime
quantity
我想用SQL将这些记录从一个表移动到另一个没有数量列的表,插入记录X次,其中X是数量的值,这样......
id name datetime quantity
----------------------------------
5 book-order 15-Mar-2010 3
# becomes
id name datetime
------------------------
5 book-order 15-Mar-2010
6 book-order 15-Mar-2010
7 book-order 15-Mar-2010
有没有办法在纯SQL中执行此操作?
答案 0 :(得分:2)
这是一种方法,假设数量不超过100:
insert into t2(name, datetime)
select name, datetime
from t1 join
(select d1*10+d2 as num
from (select 0 as n union all select 1 union all select 2 union all select 3 union all select 4 union all
select 5 union all select 6 union all select 7 union all select 8 union all select 9
) d1 cross join
(select 0 as n union all select 1 union all select 2 union all select 3 union all select 4 union all
select 5 union all select 6 union all select 7 union all select 8 union all select 9
) d2
) nums
on nums.num < t1.qty
如果数量太大,那么困难的部分就是生成一个数字表。
答案 1 :(得分:1)
如果目标表上的ID是自动增量字段,您可以考虑使用类似此查询的内容:
insert into books2 (name, datetime)
select
name, datetime
from
books inner join
(select 0 n union all select 1 union all select 2 union all select 3
union all select 4 union all select 5 union all select 6 n union all
select 7 union all select 8 union all select 9) nums
on books.quantity > nums.n;
这将根据books.quantity多次选择所有图书订单,并将它们插入到表格书2中。此查询限制为最多10个,但可以扩展。
请参阅工作小提琴here。