Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how delete parent row with all child row from other table

Tags:

php

mysql

parent_table
----------------------------------------------------------------------
id         name
1           a
2           b

child_table
---------------------------------------------------------------------
id        parent_table_id            name
1               1                      c
2               1                      d
3               1                      e
4               2                      f
5               2                      g

When I will delete first row from parent table then all child row of parent first row. how is it possible??

like image 536
Salman Quader Avatar asked Dec 24 '22 06:12

Salman Quader


2 Answers

Apart from cascade delete, you can use join, see example below:

DELETE parent_table, child_table 
FROM parent_table INNER JOIN child_table
  ON parent_table.id = child_table.parent_table_id
WHERE parent_table.id = 1
like image 58
kamal pal Avatar answered May 09 '23 16:05

kamal pal


While adding foreign key constraint use below options

ON DELETE  'CASCADE' 
ON UPDATE  'RESTRICT'

Now if you delete a parent row all associated child row will be deleted.

like image 41
Rishi Kumar Choudhary Avatar answered May 09 '23 17:05

Rishi Kumar Choudhary