![](/img/trans.png)
[英]SQL Insert multiple rows for every id returned from another table if the row does not exist for that id
[英]How do I insert multiple rows into a table for every row from another table
我有两个表:TB1和TB2。
对于TB1中的每一行,我想使用TB1中的一些值将N个行插入TB2中。 我怎么做?
例如:
For each row in TB1
{
For N in 1-10
{
insert into TB2 (col1, col2, col3, col4)
values (N, TB1.Col1, 'Good job', TB1.Col2)
}
commit;
}
用您要使用的N个数字创建另一个表(永久性或临时性),然后将此列表与TB1
交叉TB1
。 如果该表名为n_list
且其列名为N
,则:
insert into TB2
(col2, col2, col3, col4)
select
N,
TB1.Col1,
'Good job',
TB1.Col2
from
TB1
cross join n_list;
您可以使用cross join
。 设置数字表,然后:
with n as (
select 1 as n union all select 2 . . . union all select 10
)
insert into tb2 (col1, col2, col3, col4)
select n.n, TB1.Col1, 'Good job', TB1.Col2
from tb1 cross join
n;
注意事项:
n
的语法因数据库而异。 例如,MySQL不支持CTE,因此它必须是子查询。 Oracle要求from dual
,依此类推。 insert . . . select
insert . . . select
insert . . . select
,而不是insert . . . values
insert . . . values
每行的insert . . . values
。 最后,通用的SQL方法在tb1
上使用10次传递:
insert into tb2 (col1, col2, col3, col4)
select 1, TB1.Col1, 'Good job', TB1.Col2
from tb1
union all
select 2, TB1.Col1, 'Good job', TB1.Col2
from tb1
union all
. . .
select 10, TB1.Col1, 'Good job', TB1.Col2
from tb1 ;
在等待建议时,我决定四处寻找并最终使用了光标和for这样的for循环,它对我有用...尽管不确定它是否足够。 并感谢您的所有建议。
DECLARE
CURSOR myCursor IS
select col1, col2 from TB1;
tmp_rec myCursor%rowtype;
BEGIN
FOR tmp_rec in myCursor
LOOP
FOR N IN 1 .. 10
LOOP
insert into TB2 (col1, col2, col3, col4)
values (N, TB1.col1, 'Good job', TB1.col2);
END LOOP;
COMMIT;
END LOOP;
END;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.