简体   繁体   中英

MySQL - Foreign key on delete cascade - Is there a defined execution order?

I have a problem with MySQL - CASCADE ON DELETE rules on multiple tables. Obviously the execution order of "CASCADE ON DELETE"-rules depends on their order of definition.

But is this execution order well defined or depends it on the MySQL-Version?

Here is my simple example for three tables "A", "B", "C"

create table `A` (`id` NUMERIC(10,0) NOT NULL)  ENGINE=INNODB;
create table `B` (`id` NUMERIC(10,0) NOT NULL, `a_id`  NUMERIC(10,0) NOT NULL) ENGINE=INNODB;
create table `C` (`id` NUMERIC(10,0) NOT NULL, `a_id`  NUMERIC(10,0) NOT NULL, `b_id` NUMERIC(10,0) NOT NULL) ENGINE=INNODB;

ALTER TABLE `A` ADD PRIMARY KEY (`id`);
ALTER TABLE `B` ADD PRIMARY KEY (`id`);
ALTER TABLE `C` ADD PRIMARY KEY (`id`);


ALTER TABLE `C` ADD CONSTRAINT `C1` FOREIGN KEY (`a_id`) REFERENCES `A` (`id`) ON DELETE CASCADE;
ALTER TABLE `B` ADD CONSTRAINT `B1` FOREIGN KEY (`a_id`) REFERENCES `A` (`id`) ON DELETE CASCADE;
ALTER TABLE `C` ADD CONSTRAINT `C2` FOREIGN KEY (`b_id`) REFERENCES `B` (`id`);

If I insert the following data:

INSERT INTO A (id) VALUES (1);
INSERT INTO B (id, a_id) VALUES (1,1);
INSERT INTO C (id, a_id, b_id) VALUES (1,1,1);

...and try to delete the only entry in table "A":

delete from A where id=1;

...I get the following error message:

Cannot delete or update a parent row: a foreign key constraint fails (`C`, CONSTRAINT `C2` FOREIGN KEY (`b_id`) REFERENCES `B` (`id`))

But if I change the definition of the foreign key constraints to:

ALTER TABLE `C` ADD CONSTRAINT `C1` FOREIGN KEY (`a_id`) REFERENCES `A` (`id`) ON DELETE CASCADE;
ALTER TABLE `C` ADD CONSTRAINT `C2` FOREIGN KEY (`b_id`) REFERENCES `B` (`id`);
ALTER TABLE `B` ADD CONSTRAINT `B1` FOREIGN KEY (`a_id`) REFERENCES `A` (`id`) ON DELETE CASCADE;

...everything is fine...

Thanks for your help

Your ALTER TABLE table ADD CONSTRAINT foreign_key FOREIGN KEY are the same, so they cannot be the reason of the error.

(...text is removed)


Cannot explain that strange behavior. Can suggest a workaround:

SET FOREIGN_KEY_CHECKS = 0;
DELETE FROM A WHERE ID=1;
SET FOREIGN_KEY_CHECKS = 1;

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