English 中文(简体)
我该如何在MySQL中使用on delete cascade?
原标题:
  • 时间:2009-02-04 13:31:20
  •  标签:

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

最佳回答

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

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不支持外键。

问题回答

使用这个 SQL

DELETE T1, T2 FROM T1 INNER JOIN T2 ON T1.key = T2.key WHERE condition

你必须将你的Foreign Key约束定义为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
)
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.




相关问题
热门标签