外键约束ON DELETE CASCADE仍然引发约束错误

时间:2020-09-17 07:25:59

标签: sql postgresql foreign-keys constraints

对于数据库中的某些记录,我可以删除table2中的条目,这些条目已在table1中自动删除。但是在某些情况下,即使它们是相同的(相同的表,相同的外键引用,不同的值)也没有发生

我收到以下错误:

SQL Error [23503]: ERROR: update or delete on table "table2" violates foreign key constraint "table1_user_id_fk" on table "table1"
  Detail: Key (id)=(1) is still referenced from table "table1".

我使用的代码:

首先消除约束

alter table table1
drop constraint table1;

添加on delete cascade约束

alter table table1
add constraint table1_user_id_fk
foreign key (fk_id)
references table2 (id)
on delete cascade;

当我执行这样的删除操作

delete from table2 where col1 = 'someval';

它会引发上述错误。

现在我无法绕开它,因为对于不同的col1值,它会自动删除table1中的记录,并且对于某些记录会引发约束问题

0 个答案:

没有答案