且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从父表中删除只有在父表中的行,这是由子表的Foregin键引用的

更新时间:2023-02-05 10:16:53

这可能与您的数据中的一些协议。要维护子表数据,您必须执行 ON DELETE SET NULL 。这将保留数据,但将FK设置为​​ NULL 值(在子表中)。这是因为数据完整性:当您可以保存您的数据时,您的FK 不能引用不存在的父表中的行来执行 FK 约束。因此,它会被设置为 NULL



如果您想保存值的FK - 那么你绝对不应该使用FK,因为这样的行为违反了FK。那么就不要使用这个约束,但要注意可能的完整性失败。


I want to delete a row/tuple from a parent table, but it is throwing an error message because it has a FOREIGN KEY reference in its child table.

However, in my case I want to delete the record only from the parent table and maintain the data in the child table.

Is it possible to achieve this?

I know the usage of ON DELETE CASCADE, but I want to know if there is a solution for the secenario I described?

It is possible with some agreements in your data. To maintain child table data you'll have to do ON DELETE SET NULL. This will leave data, but set FK to NULL value (in child table). And that is because of data-integrity: while you can keep your data, your FK can not refer to non-existent row of parent table in terms of enforcing FK constraint. Thus, it will be set to NULL by this.

If you want to "save" value of FK - then you definitely should not use FK at all because such behavior violates what FK is. So then just don't use that constraint, but be aware of possible integrity fails.