![](/img/trans.png)
[英]How to run multiple insert statements in a transaction in postgresql?
[英]How to run dependant query in PostgreSQL transaction
我是一個 postgres 事務,我想向兩個表中的每一個插入 1 條記錄,比如說 A 和 B,B 有一個外鍵指向在同一事務中插入到 A 的記錄。
我如何在這里引用插入的記錄,以便我可以在表 B 上插入
你沒有指定實際的表結構,所以我必須編造,但是可以在一個語句中使用修改 CTE的數據來做到這一點
with new_a_row as (
insert into a (col1, col2, col3)
values ('one', 'two', 42)
returning id --<<< this is the generated primary key of the table A
)
insert into b (b_col_one, b_col_two, fk_col_to_a)
select 100, 'something', id
from new_a_row;
或者使用lastval()
並在兩個語句中執行此操作
begin;
insert into a (col1, col2, col3)
values ('one', 'two', 42);
insert into b (b_col_one, b_col_two, fk_col_to_a)
values (100, 'something', lastval());
commit;
第一個解決方案將適用於任何“生成策略”,不僅是identity
或serial
列,而且如果您使用gen_random_uuuid()
作為默認值,也適用。
第二種解決方案需要identity
或舊的serial
類型列。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.