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