2012-04-25 53 views
4
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 , CONSTRAINT FK_idparent FOREIGN KEY (idparent) REFERENCES categories (idcategories) ON DELETE CASCADE ON UPDATE CASCADE) SQL Statement: UPDATE categories SET idcategories =10 WHERE idcategories ='1'

的刪除工作,而不是如預期刪除CAT1,cat1_child將被刪除。

錯誤在哪裏? 比你。

+0

的[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

回答

7

我相信答案是在documentation(向下滾動到下):

Deviation from SQL standards: If ON UPDATE CASCADE or ON UPDATE SET NULL recurses to update the same table it has previously updated during the cascade, it acts like RESTRICT . This means that you cannot use self-referential ON UPDATE CASCADE or ON UPDATE SET NULL operations. This is to prevent infinite loops resulting from cascaded updates. A self-referential ON DELETE SET NULL , on the other hand, is possible, as is a self-referential ON DELETE CASCADE . Cascading operations may not be nested more than 15 levels deep.

演示:http://www.sqlfiddle.com/#!2/e29db/1

+0

謝謝。有沒有什麼可以做我想做的事? – 2012-04-25 18:46:36

相關問題