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?