6

我在 2 个表上有一个循环外键,所以我使用 deferable 最初的 deferred 如下:

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

到目前为止,一切都很好。但是现在当我想插入表时,我得到了外键违规,虽然我最初指定了可延迟的:

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".

有什么问题?

4

1 回答 1

5

您是否在 INSERT 之前明确打开交易?如果您不使用 BEGIN,则每个插入都是一个独立的事务,因此在每个命令的末尾强制执行外键。

于 2011-04-18T01:19:18.610 回答