如何在 mysql 中使用删除级联?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/511361/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I use on delete cascade in mysql?
提问by Marius
I have a database of components. Each component is of a specific type. That means there is a many-to-one relationship between a component and a type. When I delete a type, I would like to delete all the components which has a foreign key of that type. But if I'm not mistaken, cascade delete will delete the type when the component is deleted. Is there any way to do what I described?
我有一个组件数据库。每个组件都属于特定类型。这意味着组件和类型之间存在多对一的关系。当我删除一个类型时,我想删除所有具有该类型外键的组件。但是如果我没记错的话,级联删除会在删除组件时删除类型。有什么办法可以做到我所描述的吗?
回答by nickf
Here's what you'd include in your components table.
这是您要包含在组件表中的内容。
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
)
Just remember that you need to use the InnoDB storage engine: the default MyISAM storage engine doesn't support foreign keys.
请记住,您需要使用 InnoDB 存储引擎:默认的 MyISAM 存储引擎不支持外键。
回答by Silambarasan
You have to define your Foreign Key constraints as ON DELETE CASCADE.
您必须将外键约束定义为 ON DELETE CASCADE。
Note:You need to use InnoDB storage engine, the default MyISAM storage engine not support foreign keys relation.
注意:需要使用 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
)
回答by md asif rahman
use this sql
使用这个 sql
DELETE T1, T2 FROM T1 INNER JOIN T2 ON T1.key = T2.key WHERE condition
DELETE T1, T2 FROM T1 INNER JOIN T2 ON T1.key = T2.key WHERE 条件