0

I want to update the primary key that is also a foreign key of several tables, including some multiple foreign keys. When I try to update the primary key, MySQL fails. The minimal example below illustrates the issue.

If I create the following database:

CREATE TABLE IF NOT EXISTS Table1 (
id          INTEGER NOT NULL,
PRIMARY KEY (id));

CREATE TABLE IF NOT EXISTS Table2 (
id        INTEGER NOT NULL,
name     VARCHAR(30) NOT NULL,
PRIMARY KEY (id, name),
FOREIGN KEY (id) REFERENCES Table1(id) on UPDATE CASCADE);

CREATE TABLE IF NOT EXISTS Table3 (
id    INTEGER NOT NULL,
name  VARCHAR(30) NOT NULL,
date  DATE NOT NULL,
PRIMARY KEY (id, name, date),
FOREIGN KEY (id) REFERENCES Table1(id) on UPDATE CASCADE,
FOREIGN KEY (id, name) REFERENCES Table2(id, name) on UPDATE CASCADE);

And then I add the following data:

insert into Table1 (id) values (1);
insert into Table2 (id, name) values (1, "TEST");
insert into Table3 (id, name, date) values (1, "TEST", "2022-05-01");

I now want to:

UPDATE Table1 set id = 2 where id = 1;

I get the following error:

ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails 
(`test`.`Table3`, CONSTRAINT `Table3_ibfk_1` FOREIGN KEY (`id`) REFERENCES `Table1` 
 (`id`) ON UPDATE CASCADE)

If there is no data on Table3, the update works. What am I failing to grasp?

philipxy
  • 14,867
  • 6
  • 39
  • 83
Chicoscience
  • 975
  • 1
  • 8
  • 18
  • This looks similar to this old bug from 2005 which was closed without fixing it: https://bugs.mysql.com/bug.php?id=11305 – Bill Karwin Jul 14 '22 at 21:19
  • Ok! So it seems that it will never be fixed :-( At least the link pointed me to the "SET FOREIGN_KEY_CHECKS=0" workaround, thanks! – Chicoscience Jul 16 '22 at 01:37

1 Answers1

0

As pointed by @Bill Karwin in the comments, this is unfortunately a bug in MySQL that is not likely to be solved anytime soon.

https://bugs.mysql.com/bug.php?id=11305

A workaround is to set

SET FOREIGN_KEY_CHECKS=0

... do what needs to be done, and then revert it back:

SET FOREIGN_KEY_CHECKS=1

This is not exactly the safest option but it has been suggested earlier in this question:

Cannot add or update a child row: a foreign key constraint fails

Chicoscience
  • 975
  • 1
  • 8
  • 18