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.
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..???
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.
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.
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 ;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With