![](/img/trans.png)
[英]insert into select query from two tables into a third table that associates them
[英]How to INSERT to two tables from the same SELECT query
我在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
查詢執行兩次插入嗎?
您可以在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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.