问题
Unlike the similar other questions, I get error #1452 when updating the parent row. Why does it happen? Thank you in advance.
Here are the relevant tables:
CREATE TABLE IF NOT EXISTS `user`
(
`username` VARCHAR(100) NOT NULL,
`password` VARCHAR(200) NOT NULL,
`name` VARCHAR(100),
`surname` VARCHAR(100),
`icon` BLOB,
PRIMARY KEY (username)
);
CREATE TABLE IF NOT EXISTS `document`
(
`owner` VARCHAR(100) NOT NULL,
`name` VARCHAR(100) NOT NULL,
`sharing_link` VARCHAR(200) UNIQUE NOT NULL,
PRIMARY KEY (`owner`, `name`),
FOREIGN KEY (`owner`) REFERENCES user(`username`) ON UPDATE CASCADE
);
CREATE TABLE IF NOT EXISTS sharing
(
`sharing_user` VARCHAR(100) NOT NULL,
`document_owner` VARCHAR(100) NOT NULL,
`document_name` VARCHAR(100) NOT NULL,
PRIMARY KEY (`sharing_user`, `document_owner`, `document_name`),
FOREIGN KEY (`sharing_user`) REFERENCES user(`username`) ON UPDATE CASCADE,
FOREIGN KEY (`document_owner`, `document_name`) REFERENCES `document`(`owner`, `name`) ON UPDATE CASCADE
);
And here how to reproduce the error:
INSERT INTO `user` (`username`, `password`, `name`, `surname`, `icon`) VALUES ('fruggeri', 'fruggeri', 'Franco', 'Ruggeri', NULL);
INSERT INTO `document` (`owner`, `name`, `sharing_link`) VALUES ('fruggeri', 'document', 'sharing_link');
INSERT INTO `sharing` (`sharing_user`, `document_owner`, `document_name`) VALUES ('fruggeri', 'fruggeri', 'document');
UPDATE `user` SET `username` = 'new_fruggeri' WHERE `user`.`username` = 'fruggeri'
Resulting error:
#1452 - Cannot add or update a child row: a foreign key constraint fails (`collaborative_text_editor`.`sharing`, CONSTRAINT `sharing_ibfk_1` FOREIGN KEY (`sharing_user`) REFERENCES `user` (`username`) ON UPDATE CASCADE)
来源:https://stackoverflow.com/questions/63600963/mysql-cascade-update-failed-when-foreign-key-column-referenced-in-composite-prim