Sql 如何从同一个SELECT查询插入到两个表
我在Sql 如何从同一个SELECT查询插入到两个表,sql,postgresql,Sql,Postgresql,我在PostgreSQL中有此代码: for row in select .... from .... where .... loop insert into A(id1,id2,id3,quantity) select aa,bb,1,quantity from func1(row.idfirst); end loop; 我想用相同的查询执行另一个INSERT,以便执行以下操作: for
PostgreSQL
中有此代码:
for row in select .... from .... where ....
loop
insert into A(id1,id2,id3,quantity)
select aa,bb,1,quantity
from func1(row.idfirst);
end loop;
我想用相同的查询执行另一个INSERT
,以便执行以下操作:
for row in select .... from .... where ....
loop
insert into A(id1,id2,id3,quantity)
select aa,bb,1,quantity
from func1(row.idfirst);
insert into B(first,second,third,forth)
select aa,bb,1,quantity
from func1(row.idfirst);
end loop;
问题是,它是相同代码的冗余。。。而且func1
也是一个巨大的函数。它需要很长时间才能工作,我不会疯狂地运行两次
是否有任何解决方案可以使用相同的
select
query进行两次插入?您可以在PostgreSQL 9.1+中使用CTE,如下所示:
WITH CTE AS (
INSERT INTO A(id1,id2,id3,quantity)
SELECT aa,bb,1,quantity
FROM func1(row.idfirst);
RETURNING id1,id2,id3,quantity
)
INSERT INTO B(first,second,third,forth)
SELECT id1,id2,id3,quantity
FROM CTE;
我不认为我们可以一次插入多个表。但是,在同一个表中插入多个值是可能的。我认为使用
CTE
(with
)是可能的。我只是不知道如何做。另一个可能的解决方案是在插入a时触发。它是否适合您取决于表的语义,我们不知道。