3

I want to delete records in parent table as well as child table using only one query. I m having the child table name CHILD1_TABLE in the Parent table PARENT_TABLE in the field name of TABLENAME. The parent table contains more child tables.I want to delete only one record from one of the child table as well parent table. The common field is ID in both child and parent tables. I write my query like this,

DELETE PARENT.*,CHILD.* 
FROM PARENT_TABLE PARENT 
INNER JOIN (SELECT TABLENAME FROM PARENT_TABLE WHERE ID='CHILD1-001') CHILD 
ON PARENT.ID=CHILD.ID 
WHERE PARENT.ID='CHILD1-001'

But it not works. Can anybody help me?

Arion
  • 31,011
  • 10
  • 70
  • 88
Sangeetha Krishnan
  • 941
  • 1
  • 12
  • 17
  • Maybe some of the ideas here help - [How to have Dynamic SQL in mysql stored procedure](http://stackoverflow.com/questions/190776/how-to-have-dynamic-sql-in-mysql-stored-procedure) – Randall Nov 29 '16 at 22:29

3 Answers3

2

What about this:

DELETE PARENT.*,CHILD.* 
FROM PARENT_TABLE PARENT 
INNER JOIN (SELECT * FROM (SELECT TABLENAME FROM PARENT_TABLE WHERE ID='CHILD1-001') AS CHILD)  
ON PARENT.ID=CHILD.ID 
WHERE PARENT.ID='CHILD1-001'
Code Prank
  • 4,209
  • 5
  • 31
  • 47
0

Why not use ON DELETE CASCADE?

Euclides Mulémbwè
  • 1,677
  • 11
  • 18
0
DELETE PARENT.*,CHILD.* 
FROM PARENT_TABLE PARENT 
INNER JOIN (SELECT * FROM (SELECT TABLENAME FROM PARENT_TABLE WHERE ID='CHILD1-001') AS a)  as child
ON PARENT.ID=CHILD.ID 
WHERE PARENT.ID='CHILD1-001'

I am not sure for this query but give it a try.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Ankit Sharma
  • 3,923
  • 2
  • 29
  • 49