【发布时间】:2018-03-22 17:31:29
【问题描述】:
我正在使用“insert ... select ... where exists ...”将行批量插入到表中,同时忽略 FK 约束无效的行。但是,当有一个并发事务刚刚删除了引用表中的一行时,这不起作用。
考虑以下 psql 会话:
第 1 节:
coudy=# create table a (x int primary key);
CREATE TABLE
coudy=# create table b (x int, foreign key (x) references a);
CREATE TABLE
coudy=# insert into a values (1);
INSERT 0 1
coudy=# begin;
BEGIN
coudy=# delete from a where x = 1;
DELETE 1
第 2 节:
coudy=# begin;
BEGIN
coudy=# insert into b select v.x from (values (1)) v (x) where exists (select 1 from a where a.x = v.x);
这会正确阻止会话 2。但是,在会话 1 中提交后,会话 2 现在意外失败:
ERROR: insert or update on table "b" violates foreign key constraint "b_x_fkey"
DETAIL: Key (x)=(1) is not present in table "a".
我希望该行会被过滤掉,因此不会被插入。在我的实际场景中,这是批量插入,所以理想情况下我希望避免重试。
提高隔离级别没有帮助。
【问题讨论】:
标签: postgresql