CREATE TABLE `categories` (
`idcategories` INT NOT NULL AUTO_INCREMENT ,
`idparent` INT NULL ,
`description` VARCHAR(45) NULL ,
PRIMARY KEY (`idcategories`));
ALTER TABLE `categories`
ADD CONSTRAINT `FK_idparent`
FOREIGN KEY (`idparent`)
REFERENCES `ilmercatinodelpulcino`.`categories` (`idcategories`)
ON DELETE CASCADE
ON UPDATE CASCADE
, ADD INDEX `FK_idparent` (`idparent` ASC) ;
INSERT INTO `categories` (`idcategories`, `description`)
VALUES (1, 'cat1');
INSERT INTO `categories` (`idcategories`, `idparent`, `description`)
VALUES (2, 1, 'cat1_child');
因此,此表代表具有ID和自指向父ID的类别。 我已经插入了一个类别cat1和一个子类别cat1_child,父母id为cat1。错误1451:无法删除或更新父行:外键约束失败
现在,我希望能够将cat1的idcategory从1更改为10,并且因为我在更新CASCADE上设置了外键,所以我期望cat1_child的idparent也将设置为10。 但是当我做:
UPDATE `categories` SET `idcategories`=10 WHERE `idcategories`='1';
我得到一个错误:
ERROR 1451: Cannot delete or update a parent row: a foreign key constraint fails (
categories
, CONSTRAINTFK_idparent
FOREIGN KEY (idparent
) REFERENCEScategories
(idcategories
) ON DELETE CASCADE ON UPDATE CASCADE) SQL Statement: UPDATEcategories
SETidcategories
=10 WHEREidcategories
='1'
的删除工作,而不是如预期删除CAT1,cat1_child将被删除。
错误在哪里? 比你。
的[MySQL的可能重复:ON UPDATE CASCADE一个简单的表“ID |父母| text“,not possible?](http://stackoverflow.com/questions/5446517/mysql-on-update-cascade-for-a-simple-table-idparenttext-not-possible) – mellamokb 2012-04-25 17:45:07