How do I use on delete cascade in mysql?

微笑、不失礼 提交于 2019-11-26 02:12:00

问题


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?


回答1:


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.




回答2:


You have to define your Foreign Key constraints as ON DELETE CASCADE.

Note: You need to use InnoDB storage engine, the default MyISAM storage engine not support foreign keys relation.

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
)



回答3:


use this sql

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



来源:https://stackoverflow.com/questions/511361/how-do-i-use-on-delete-cascade-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!