Search code examples
mysqlsql-deletecascade

I need to delete multiple rows from multiple tables using foreign Key


I have three different tables, tbl1, tbl2, and tbl3 for example. I need to delete rows from each of the three tables. Only problem is, there are foreign key constraints between each of the tables. If I delete a row from tbl1, the delete cascades and deletes all rows from from tbl2 and tbl3 that referenced the deleted row in tbl1. How can I delete only specific rows?


Solution

  • Here's one approach:

     DELETE FROM tbl3 WHERE tbl3.tbl1_id = 'foo';
     DELETE FROM tbl2 WHERE tbl2.tbl1_id = 'foo';
     DELETE FROM tbl1 WHERE tbl1.tbl1_id = 'foo';