postgresql和Delete语句违反了外键约束

Pom*_*dou 4 sql postgresql referential-integrity foreign-keys

我的删除声明有问题.

我有两张桌子:

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
);
Run Code Online (Sandbox Code Playgroud)

当我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"
Run Code Online (Sandbox Code Playgroud)

我想我理解错误:vehicule从表中删除a之后vehicule_loan,vehiculein vehicule_uid会指向什么.

但有没有办法保持行vehicule_uid

dan*_*era 5

您应该允许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
);
Run Code Online (Sandbox Code Playgroud)

使用此设置时,删除数据库vehicule_loanvehicule_uid保留的所有引用行中的行.