I am trying to delete from multiple tables. Here's what my tables look like
A_has_B ---- B ---- C_has_B
(many to many) (many to many)
I am trying to delete all rows from A_has_B, B and C_has_B given the ID of a record in B. I am using MySQL with the innodb storage engine with foreign keys defined for A_has_B and C_has_B referencing the IDs in B.
I am trying to perform my delete like so:
DELETE A_has_B.*, C_has_B.*, B.*
FROM
A
join
B
on (B.B_id = A.B_id)
join
C
on (C.B_id = B.B_id)
where B.B_id IN(1,2, 4);
The problem is that when I execute the query, mysql complains:
Error Code: 1451. Cannot delete or update a parent row: a foreign key constraint fails (`db`.`C`, CONSTRAINT `fk_C` FOREIGN KEY (`B_id`) REFERENCES `B` (`B_id`) ON DELETE NO ACTION ON UPDATE NO)
How can I go about fixing this?
You can specify the "delete cascade" on the foreign key. When you delete the parent row, the mysql engine will delete the records in the related child tables
Do the deletes in separate statments and it will work.
The simplest way would be to delete from each table individually:
MySQL also allows you to delete from multiple tables in one statement. But there is no way to control the order of the deletions. From the manual:
Actually, in MySQL, you can turn off checks for foreign key constraints
The statement on the first line forces MySQL server to turn off foreign key checks and the last line turns them back on (very important). Two things to keep in mind: