微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我的删除声明有问题.

我有两张桌子:

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_loan中删除一个vehicule时,我希望保留表vehicule_uid中的引用行.

但是当我尝试删除一个时,我收到此错误

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

我想我理解错误
我从表vehicule_loan中删除一个车辆后,vehicule_uid中的车辆将指向什么.

但是有没有办法将行保存在vehicule_uid中?

解决方法

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

我引用第5.3. Constraints from the PostgreSQL manual章:

There are two other options: SET NULL and SET DEFAULT. These cause the
referencing columns to be set to nulls or default values,
respectively,when the referenced row is deleted.

看起来像这样:

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中的所有引用行都保留在数据库中.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐