简体   繁体   English

如何在 PostgreSQL 事务中运行依赖查询

[英]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.我是一个 postgres 事务,我想向两个表中的每一个插入 1 条记录,比如说 A 和 B,B 有一个外键指向在同一事务中插入到 A 的记录。

How do I refer the inserted record here so that I can insert on table B我如何在这里引用插入的记录,以便我可以在表 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你没有指定实际的表结构,所以我必须编造,但是可以在一个语句中使用修改 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;

Alternatively use lastval() and do this in two statements或者使用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;

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.第一个解决方案将适用于任何“生成策略”,不仅是identityserial列,而且如果您使用gen_random_uuuid()作为默认值,也适用。

The second solution requires an identity or the old serial type column.第二种解决方案需要identity或旧的serial类型列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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