简体   繁体   中英

MySQL cascade delete on self-referencing parent-child table?

I have this MySql database table:

tbl_project
id
project_name
parent_id

If a project is a 'parent', parent_id is 0 .

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.

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. Foreign keys ignore NULL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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