I have a table called mail with a foreign key column called deletedBy which references the users table by pk. when I create a new mail i want to set this field to null as the mail is undeleted, however when i do i get an foreign key constraint failure error.
I totally understand the error, but how do i get around it?
table:-
CREATE TABLE `mail` (
`pk` int(10) unsigned NOT NULL AUTO_INCREMENT,
`from` int(11) unsigned NOT NULL,
`to` int(11) unsigned NOT NULL,
`subject` varchar(255) NOT NULL,
`message` text NOT NULL,
`dt` datetime NOT NULL,
`read` enum('0','1') NOT NULL DEFAULT '0',
`deletedby` int(11) unsigned DEFAULT '0',
PRIMARY KEY (`pk`),
KEY `from_mail__users_pk` (`from`),
KEY `to_mail__users_pk` (`to`),
KEY `deletedby_mail__users_pk` (`deletedby`),
CONSTRAINT `deletedby_mail__users_pk` FOREIGN KEY (`deletedby`) REFERENCES `user` (`pk`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `from_mail__users_pk` FOREIGN KEY (`from`) REFERENCES `user` (`pk`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `to_mail__users_pk` FOREIGN KEY (`to`) REFERENCES `user` (`pk`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8 COLLATE=utf8_bin
error message:-
ERROR 1452: Cannot add or update a child row: a foreign key constraint fails (`ajfit`.`mail`, CONSTRAINT `deletedby_mail__users_pk` FOREIGN KEY (`deletedby`) REFERENCES `user` (`pk`) ON DELETE NO ACTION ON UPDATE NO ACTION)
SQL Statement:
INSERT INTO `ajfit`.`mail` (`from`, `to`, `subject`, `message`, `read`) VALUES (31, 30, 'test', 'test', '0')
Thanks
Andrew
Because you are not providing a value for
deletedby, theDEFAULTvalue of0used. But there is (presumably) no record in theusertable with apkof 0 and therefore the foreign key constraint (correctly) fails.As you have said yourself, you want
deletedbyto have aDEFAULTvalue ofNULLso that the foreign key constraint is not checked until an alternative value is provided: