Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete automatically all reference rows if parent row get deleted in mysql?

I have a database which contains around 50 tables.

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

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.

like image 799
Aamir Avatar asked Jan 23 '14 06:01

Aamir


People also ask

Can we delete a row from parent table without deleting the rows from child table?

Don't do it! You can drop foreign keys for the time being and drop from parent row, but this will create orphan records which is a bad thing. Well, that's why it's called Referential Integrity, it's used to prevent such stupid things :-) If we are deleting parent, Why that should be associated to a child..???

How do I delete parent and child records in MySQL?

ON DELETE CASCADE clause in MySQL is used to automatically remove the matching records from the child table when we delete the rows from the parent table. It is a kind of referential action related to the foreign key.

What if I delete a row containing a foreign key to another table?

Suppose there is a main table containing a primary key and there is another table which contains a foreign key to this main table. So if we delete the row of main table it will delete the child table also.


1 Answers

You can do with ON DELETE CASCADE.

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

OR

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 ;
like image 85
Saharsh Shah Avatar answered Oct 20 '22 02:10

Saharsh Shah