4

我的删除语句有问题。

我有两张桌子:

table vehicule_loan(
    vehicule TEXT NOT NULL UNIQUE,
);

table vehicule_uid (
    id UUID NOT NULL DEFAULT uuid_generate_v4(),
    vehicule TEXT NOT NULL REFERENCES vehicule_loan(vehicule) ON DELETE NO ACTION
);

当我vehicule从表中删除 a 时,vehicule_loan我希望vehicule_uid保留表中的引用行。

但是当我尝试删除一个时,我得到了这个错误:

ERROR:  update or delete on table "vehicule_loan" violates foreign key constraint "vehicule_uid_vehicule_fkey" on table "vehicule_uid"

我想我理解错误:vehicule从 table中删除 a 后vehicule_loanvehiculeinvehicule_uid将指向任何内容。

但是有没有办法保留行vehicule_uid

4

1 回答 1

6

您应该允许NULL外键属性中的值并将外键约束定义为ON DELETE SET NULL.

我引用第5.3 章。来自 PostgreSQL 手册的约束

还有两个其他选项:SET NULL 和 SET DEFAULT。当引用的行被删除时,这些会导致引用列分别设置为空值或默认值。

可能看起来像这样:

table vehicule_uid (
    id uuid NOT NULL DEFAULT uuid_generate_v4(),
    vehicule text REFERENCES vehicule_loan(vehicule) ON DELETE SET NULL
);

使用此设置,当您删除vehicule_loan所有引用行中的行时,vehicule_uid保留在数据库中。

于 2012-02-05T16:19:18.620 回答