Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use delete cascade on MySQL MyISAM storage engine?

I have one table that I had called equipment, and 8 other tables that I had called equipment_child1 and so on until equipment_child8.

The commom field between all that tables is cod_equip, with this field I 'm able to identify all my child equipment tables with equipment parent table.

I need to delete data from equipment when the equipment is moved, but I need to delete data in all my tables equipment_child1 to equipment_child8.

then I remenber I had used DELETE CASCADE in innoDB engine, but now I'm using MyISAM engina, is that a problem?

Any help, will really clarify ...

like image 492
devasia2112 Avatar asked Mar 17 '11 17:03

devasia2112


1 Answers

Yes. Simply you can't with that engine.

edit. You could write a trigger that once you delete a record in your table delete all child records in all the other tables.

Ok. I wrote you an example:

 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;

Hope that it helps.

edit. Obviously it works even if you delete more id from table1 at the same time:

delete from tab1 where id in (2,3,4);
like image 89
Nicola Cossu Avatar answered Oct 14 '22 17:10

Nicola Cossu