外键关系在mysql中不起作用

时间:2018-05-03 17:10:30

标签: mysql foreign-keys

这里我正在为我的SQL做外键关系,我有3个表

  1. 产品
  2. 报价
  3. 这里product表是一个主表,galleryoffer表是子表,现在我试图删除主表项,但它没有发生我收到的错误就像

      

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

        CREATE TABLE `product` (
     `productId` int(11) NOT NULL AUTO_INCREMENT,
     `name` varchar(100) COLLATE utf16_bin NOT NULL,
     `price` decimal(10,0) NOT NULL,
     `regOn` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
     PRIMARY KEY (`productId`)
    ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf16 COLLATE=utf16_bin
    
    CREATE TABLE `offer` (
     `offerId` int(11) NOT NULL AUTO_INCREMENT,
     `productId` int(11) NOT NULL,
     `offerpercentage` text COLLATE utf16_bin NOT NULL,
     PRIMARY KEY (`offerId`),
     KEY `productId` (`productId`),
     CONSTRAINT `offer_ibfk_1` FOREIGN KEY (`productId`) REFERENCES `product` (`productId`)
    ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf16 COLLATE=utf16_bin
    
    CREATE TABLE `gallery` (
     `galleryId` int(11) NOT NULL AUTO_INCREMENT,
     `productId` int(11) NOT NULL,
     `galleryName` text COLLATE utf16_bin NOT NULL,
     PRIMARY KEY (`galleryId`),
     KEY `productId` (`productId`),
     CONSTRAINT `gallery_ibfk_1` FOREIGN KEY (`productId`) REFERENCES `product` (`productId`)
    ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf16 COLLATE=utf16_bin
    
      

    预期输出

    Suppose I am deleting master table entry means i have to delete all child tables entry also
    

1 个答案:

答案 0 :(得分:0)

您需要将ON DELETE CASCADE应用于外键引用。

CREATE TABLE `product` (
 `productId` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(100) COLLATE utf16_bin NOT NULL,
 `price` decimal(10,0) NOT NULL,
 `regOn` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
 PRIMARY KEY (`productId`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf16 COLLATE=utf16_bin

CREATE TABLE `offer` (
 `offerId` int(11) NOT NULL AUTO_INCREMENT,
 `productId` int(11) NOT NULL,
 `offerpercentage` text COLLATE utf16_bin NOT NULL,
 PRIMARY KEY (`offerId`),
 KEY `productId` (`productId`),
 CONSTRAINT `offer_ibfk_1` FOREIGN KEY (`productId`) REFERENCES `product` (`productId`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf16 COLLATE=utf16_bin

CREATE TABLE `gallery` (
 `galleryId` int(11) NOT NULL AUTO_INCREMENT,
 `productId` int(11) NOT NULL,
 `galleryName` text COLLATE utf16_bin NOT NULL,
 PRIMARY KEY (`galleryId`),
 KEY `productId` (`productId`),
 CONSTRAINT `gallery_ibfk_1` FOREIGN KEY (`productId`) REFERENCES `product` (`productId`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf16 COLLATE=utf16_bin

这告诉MySQL当父项被删除时,删除引用子项。