简体   繁体   English

自引用父子表上的MySQL级联删除?

[英]MySQL cascade delete on self-referencing parent-child table?

I have this MySql database table: 我有这个MySql数据库表:

tbl_project
id
project_name
parent_id

If a project is a 'parent', parent_id is 0 . 如果项目是“父”,则parent_id0

Now I'm trying to add a self referencing foreign key 现在我正在尝试添加自引用外键

CONSTRAINT `FK_tbl_project_tbl_project` FOREIGN KEY (`parent_id`) REFERENCES `tbl_project` (`id`) ON DELETE CASCADE

When I try to insert a new record, 当我尝试插入新记录时

SQL Error (1452): Cannot add or update a child row: a foreign key constraint fails (mydbname.#sql-3539_d7d, CONSTRAINT FK_tbl_project_tbl_project FOREIGN KEY (parent_id) REFERENCES tbl_project (id) ON DELETE CASCADE)

Basically I just want all the children to be deleted when I delete the parent. 基本上我只想在删除父项时删除所有子项。 What am I missing here? 我在这里错过了什么?

When you enter any value into the parent_id column of a new row, the foreign key requires that there is a row where id has that value, because that's how foreign keys work. 当您在新行的parent_id列中输入任何值时,外键要求存在id具有该值的行,因为这是外键的工作方式。

If you want to use a foreign key with your self-referencing relationship, you should use NULL instead of 0 for the parent_id of a row that has no parent to reference. 如果要使用具有自引用关系的外键,则应该对没有父引用的行的parent_id使用NULL而不是0。 Foreign keys ignore NULL. 外键忽略NULL。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM