我在数据库中创建了一个名为category的表:
CREATE TABLE IF NOT EXISTS `category`
( `categoryName` varchar(128) ,
`subcategoryName` varchar(128) ,
PRIMARY KEY (`categoryName`) )
ENGINE=InnoDB DEFAULT CHARSET=latin1
此表中的类别可能是该字段中另一个类别的子类别。因此,子类别是类别的FK。初始化:
ALTER TABLE `category` ADD FOREIGN KEY (`subcategoryName`) REFERENCES `category`(`categoryName`) ON DELETE RESTRICT ON UPDATE RESTRICT;
所以我尝试像这样在表中插入值:
INSERT INTO `category` (`categoryName`, `subcategoryName`) VALUES
( 'Literature','Satire'),
( 'Science','Mathematics'),
( 'Science','Physics');
这给了我这个错误:
#1452 - Cannot add or update a child row: a foreign key constraint fails (`php_beginner_crud_level_1`.`category`, CONSTRAINT `category_ibfk_1` FOREIGN KEY (`subcategoryName`) REFERENCES `category` (`categoryName`))
关于为什么会发生这种情况以及如何解决这个问题的任何想法?