如果在mysql中删除父行,如何自动删除所有引用行?

How to delete automatically all reference rows if parent row get deleted in mysql?(如果在mysql中删除父行,如何自动删除所有引用行?)
本文介绍了如果在mysql中删除父行,如何自动删除所有引用行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含大约 50 个表的数据库.

I have a database which contains around 50 tables.

假设我有一个名为 parent 的表,其 id 主键和 24 个大约参考此父表的子表.

Suppose I have a table named parent with id primary key and 24 approx child tables with reference to this parent table.

我没有使用删除级联.我已经搜索过关于连接可以在所有子表中执行删除.但是加入 20-30 张桌子?太多了.

I haven't used on delete cascade. I have already searched about doing joins can perform delete in all child table. But join on 20-30 tables? Its too much.

如果父级被删除,请告诉我是否有任何其他解决方案可以删除所有这些子行.

Please let me know is there any other solution to delete all this child rows if parent get deleted.

推荐答案

您可以使用 ON DELETE CASCADE.

ALTER TABLE childTable
  ADD CONSTRAINT `FK_key` FOREIGN KEY (`childColumnName`) 
  REFERENCES parentTable(`parentColumnName`) ON UPDATE CASCADE ON DELETE CASCADE

父表上创建AFTER DELETE TRIGGER.添加子表的 DELETE 查询.

Create AFTER DELETE TRIGGER on parent table. Add DELETE queries of child tables.

DELIMITER $$

CREATE
    TRIGGER `tn_aur_department_master` AFTER DELETE ON `tn_parentTable` 
    FOR EACH ROW BEGIN
        DELETE FROM childTable WHERE parentId = old.parentId;
    END;
$$

DELIMITER ;

这篇关于如果在mysql中删除父行,如何自动删除所有引用行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)