【问题标题】:How to use delete cascade on MySQL MyISAM storage engine?如何在 MySQL MyISAM 存储引擎上使用删除级联?
【发布时间】:2011-07-17 14:29:13
【问题描述】:

我有一个表称为 equipment,还有 8 个表称为 equipment_child1,依此类推,直到 equipment_child8。

所有表之间的公共字段是 cod_equip,通过该字段,我可以使用 设备 识别我的所有 子设备 表父表。

当 设备 被移动时,我需要从 设备 中删除数据,但我需要删除我所有表中的数据设备_child1 到 device_child8 .

然后我记得我在 innoDB 引擎中使用了 DELETE CASCADE,但现在我使用的是 MyISAM 引擎,有问题吗?

任何帮助,都会真正澄清......

【问题讨论】:

    标签: mysql cascading-deletes


    【解决方案1】:

    是的。只是你不能用那个引擎。

    编辑。您可以编写一个触发器,一旦您删除表中的记录,就会删除所有其他表中的所有子记录。

    好的。我给你写了一个例子:

     create table tab1 (
     id int )
     engine = myisam;
    
    insert into tab1 values (1),(2),(3),(4); 
    
     create table tab2(
     id int not null auto_increment primary key,
     id_tab1 int
     ) engine = myisam;
    
     insert into tab2 (id_tab1) values (1),(2),(2),(3),(4);
    
     create table tab3(
     id int not null auto_increment primary key,
     id_tab1 int
     ) engine = myisam;
    
      insert into tab3 (id_tab1) values (1),(2),(2),(3),(2);
    
    
    delimiter //
    create trigger deletecascade after delete on tab1
    for each row
    begin
    delete from tab2 where id_tab1 = old.id;
    delete from tab3 where id_tab1 = old.id;
    end; //
    delimiter ;
    
    delete from tab1 where id = 2;
    

    希望对你有帮助。

    编辑。显然,即使您同时从 table1 中删除更多 id 也可以:

    delete from tab1 where id in (2,3,4);
    

    【讨论】:

    • 知道如何用触发器做到这一点吗?
    • 哇,很好很简单的解释,我会适应我的代码,真的很完美!谢谢@nick
    • @Sanjay:很高兴你发现它有用。 :)
    • 如果您可以使用将已删除信息存储在单独表中的触发器来更新它,那就太棒了!
    猜你喜欢
    • 2016-12-23
    • 2013-07-12
    • 2011-04-01
    • 1970-01-01
    • 2011-03-25
    • 1970-01-01
    • 2019-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多