2012-04-25 90 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

相关问题