加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-13 15:56:19 所属栏目:百科 来源:网络整理
导读:我的删除声明有问题. 我有两张桌子: 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); 当我从
我的删除声明有问题.

我有两张桌子:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读