简体   繁体   中英

How to run dependant query in PostgreSQL transaction

I an postgres transaction I want to insert 1 record each to two tables say A & B, B has a foreign key to the record inserted to A in the same transaction.

How do I refer the inserted record here so that I can insert on table B

You didn't specify the actual table structure, so I have to make things up, but a data modifying CTE can be used to do that in one statement

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;

Alternatively use lastval() and do this in two statements

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;

The first solution will work with any "generation strategy" not only identity or serial columns but also if you eg use gen_random_uuuid() as a default value.

The second solution requires an identity or the old serial type column.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM