如何在mysql中使用删除级联?

时间:2009-02-04 13:31:21

标签: mysql sql foreign-keys cascade

我有一个组件数据库。每个组件都是特定类型。这意味着组件和类型之间存在多对一关系。当我删除一个类型时,我想删除所有具有该类型外键的组件。但是如果我没弄错的话,级联删除会在删除组件时删除该类型。有没有办法做我描述的事情?

4 个答案:

答案 0 :(得分:55)

以下是您在组件表中包含的内容。

CREATE TABLE `components` (
    `id` int(10) unsigned NOT NULL auto_increment,
    `typeId` int(10) unsigned NOT NULL,
    `moreInfo` VARCHAR(32), 
    -- etc
    PRIMARY KEY (`id`),
    KEY `type` (`typeId`)
    CONSTRAINT `myForeignKey` FOREIGN KEY (`typeId`)
      REFERENCES `types` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
)

请记住,您需要使用InnoDB存储引擎:默认的MyISAM存储引擎不支持外键。

答案 1 :(得分:2)

您必须将外键约束定义为ON DELETE CASCADE。

注意:你需要使用InnoDB存储引擎,他默认MyISAM存储引擎不支持外键关系。

CREATE TABLE `table2` (
`id` int(11) NOT NULL auto_increment,
`name` int(11) NOT NULL,

PRIMARY KEY (`id`),
KEY `ids` (`ids`)
CONSTRAINT `foreign` FOREIGN KEY (`ids`)
  REFERENCES `table2` (`ids`) ON DELETE CASCADE ON UPDATE CASCADE
)

答案 2 :(得分:0)

使用此sql

删除T1,T2 来自T1 INNER JOIN T2 ON T1.key = T2.key 条件

答案 3 :(得分:0)

Step 1. Create the buildings table:

CREATE TABLE buildings (
  building_no INT PRIMARY KEY AUTO_INCREMENT,
  building_name VARCHAR(255) NOT NULL,
  address VARCHAR(255) NOT NULL
);

Step 2. Create the rooms table:

CREATE TABLE rooms (
  room_no INT PRIMARY KEY AUTO_INCREMENT,
  room_name VARCHAR(255) NOT NULL,
  building_no INT NOT NULL,
  FOREIGN KEY (building_no)
    REFERENCES buildings (building_no)
    ON DELETE CASCADE
);

Notice that the ON DELETE CASCADE  clause at the end of the foreign key constraint 
definition.