我在2个表上有一个循环外键,所以我使用deferrable最初推迟如下:
uni=# create table vorlesungen (vnr integer primary key, gelesenvon integer);
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "vorlesungen_pkey" for table "vorlesungen"
CREATE TABLE
uni=# create table professoren (pnr integer primary key, lieblingsvo integer);
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "professoren_pkey" for table "professoren"
CREATE TABLE
uni=# alter table professoren add constraint vfk foreign key (lieblingsvo) references vorlesungen (vnr) deferrable initially deferred;
ALTER TABLE
uni=# alter table vorlesungen add constraint pfk foreign key (gelesenvon) references professoren (pnr) deferrable initially deferred;
ALTER TABLE
到目前为止一切顺利。
但是现在当我想插入表格时,我得到了外键违规,尽管我指定了deferredrable最初推迟:
uni=# insert into vorlesungen values (1, 1);
ERROR: insert or update on table "vorlesungen" violates foreign key constraint "pfk"
DETAIL: Key (gelesenvon)=(1) is not present in table "professoren".
uni=# insert into professoren values (1, 1);
ERROR: insert or update on table "professoren" violates foreign key constraint "vfk"
DETAIL: Key (lieblingsvo)=(1) is not present in table "vorlesungen".
问题是什么?
答案 0 :(得分:5)
您是否明确在开启交易之前 INSERT语句中?如果不使用BEGIN,则每个插入都是一个独立的事务,因此在每个命令的末尾强制执行外键。