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
后,vehicule_uid
中的 vehicule
将不指向任何内容。
但是有没有办法将行保留在 vehicule_uid
中?
I have a problem with my delete statement.
I have two tables:
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
);
When I delete a vehicule
from the table vehicule_loan
I want that referencing rows in the table vehicule_uid
are kept.
But when I try to delete one I get this error:
ERROR: update or delete on table "vehicule_loan" violates foreign key constraint "vehicule_uid_vehicule_fkey" on table "vehicule_uid"
I think I understand the error:
After I delete a vehicule
from the table vehicule_loan
, the vehicule
in vehicule_uid
would point to nothing.
But is there a way to keep the rows in vehicule_uid
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该允许外键属性中存在
NULL
值,并将外键约束定义为ON DELETE SET NULL
。我引用章节5.3。 PostgreSQL 手册中的约束:
可能如下所示:
使用此设置,当您删除
vehicule_loan
中的行时,vehicule_uid
中的所有引用行仍保留在数据库中。You should allow
NULL
values in the foreign key attribute and define the foreign key constraint asON DELETE SET NULL
.I quote chapter 5.3. Constraints from the PostgreSQL manual:
Could look like this:
With this setting, when you delete a row in
vehicule_loan
all referencing rows invehicule_uid
remain in database.