无法删除或更新父行:外键约束失败

时间:2014-07-09 06:04:51

标签: mysql sql

做的时候:

DELETE FROM `salon_connection`.`attribute` WHERE `Id`='4'

它出现以下错误:

ERROR 1451: Cannot delete or update a parent row: a foreign key constraint fails (`salon_connection`.`datainfo`, CONSTRAINT `DataAttributeId` FOREIGN KEY (`DataAttributeId`) REFERENCES `attribute` (`Id`) ON DELETE NO ACTION ON UPDATE NO ACTION)

SQL语句:

以下是我的表格:

   delimiter $$

    CREATE TABLE `tabs` (
     `Id` int(11) NOT NULL,
     `TabsName` varchar(450) DEFAULT NULL,
     PRIMARY KEY (`Id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1$$


    delimiter $$

    CREATE TABLE `category` (
    `Id` int(11) NOT NULL AUTO_INCREMENT,
    `CategoryName` varchar(450) DEFAULT NULL,
    `TabsId` int(11) DEFAULT NULL,
     PRIMARY KEY (`Id`),
     KEY `TabsId` (`TabsId`),
     CONSTRAINT `TabsId` FOREIGN KEY (`TabsId`) REFERENCES `tabs` (`Id`) ON DELETE NO   

     ACTION ON UPDATE NO ACTION
     ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1$$



    delimiter $$

     CREATE TABLE `subcategory` (
      `Id` int(11) NOT NULL AUTO_INCREMENT,
      `SubCategoryName` varchar(450) DEFAULT NULL,
      `TabsCategoryId` int(11) DEFAULT NULL,
      `CategoryId` int(11) DEFAULT NULL,
     PRIMARY KEY (`Id`),
     KEY `TabsCategoryId` (`TabsCategoryId`),
     KEY `CategoryId` (`CategoryId`),
     CONSTRAINT `CategoryId` FOREIGN KEY (`CategoryId`) REFERENCES `category` (`Id`) ON   

     DELETE NO ACTION ON UPDATE NO ACTION,
     CONSTRAINT `TabsCategoryId` FOREIGN KEY (`TabsCategoryId`) REFERENCES `tabs` (`Id`) ON  

     DELETE NO ACTION ON UPDATE NO ACTION
     ) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=latin1$$



    CREATE TABLE `attribute` (
     `Id` int(11) NOT NULL AUTO_INCREMENT,
     `AttributeName` varchar(450) DEFAULT NULL,
     `TabsCategorySubId` int(11) DEFAULT NULL,
     `CategorySubId` int(11) DEFAULT NULL,
     `SubCategoryId` int(11) DEFAULT NULL,
     PRIMARY KEY (`Id`),
     KEY `TabsCategorySubId` (`TabsCategorySubId`),
     KEY `CategorySubId` (`CategorySubId`),
     KEY `SubCategoryId` (`SubCategoryId`),
     CONSTRAINT `CategorySubId` FOREIGN KEY (`CategorySubId`) REFERENCES `category` (`Id`)  

    ON DELETE NO ACTION ON UPDATE NO ACTION,
    CONSTRAINT `SubCategoryId` FOREIGN KEY (`SubCategoryId`) REFERENCES `subcategory`  

    (`Id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
    CONSTRAINT `TabsCategorySubId` FOREIGN KEY (`TabsCategorySubId`) REFERENCES `tabs`  

    (`Id`) ON DELETE NO ACTION ON UPDATE NO ACTION
    ) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=latin1$$

请帮忙

1 个答案:

答案 0 :(得分:2)

这是强制执行的外键。

您无法从attributes中的行中删除仍在使用(即引用)的datainfo行。

您必须先删除所有这些行,或将它们指向另一个属性。

如果您希望在删除父行时自动删除它们,您可以指定约束应该级联删除(但这是一个有潜在危险的设置)。