Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL delete row from multiple tables

Is this the correct way to do it?

DELETE t1, t2, t3, t4 FROM 
  table1 as t1 
  INNER JOIN  table2 as t2 on t1.id = t2.id
  INNER JOIN  table3 as t3 on t1.id=t3.id
  INNER JOIN  table4 as t4 on t1.id=t4.id
  WHERE  t1.username='%s' AND t1.id='%s'
like image 906
salmane Avatar asked Feb 06 '10 19:02

salmane


2 Answers

Yes, that is correct. It works fine here:

CREATE TABLE table1 (id int, username nvarchar(30));
CREATE TABLE table2 (id int);
CREATE TABLE table3 (id int);
CREATE TABLE table4 (id int);

INSERT INTO table1 VALUES (1, 'Foo'),(2, 'Bar');
INSERT INTO table2 VALUES (1),(2);
INSERT INTO table3 VALUES (1),(2);
INSERT INTO table4 VALUES (1),(2);

SELECT COUNT(*) FROM table1;
2
SELECT COUNT(*) FROM table2;
2
SELECT COUNT(*) FROM table3;
2
SELECT COUNT(*) FROM table4;
2

DELETE t1, t2, t3, t4 FROM
  table1 as t1
  INNER JOIN  table2 as t2 on t1.id = t2.id
  INNER JOIN  table3 as t3 on t1.id=t3.id
  INNER JOIN  table4 as t4 on t1.id=t4.id
  WHERE  t1.username='Foo' AND t1.id='1';

SELECT COUNT(*) FROM table1;
1
SELECT COUNT(*) FROM table2;
1
SELECT COUNT(*) FROM table3;
1
SELECT COUNT(*) FROM table4;
1

If it's not working for you, perhaps you can modify this example to show what problem you are having.

like image 105
Mark Byers Avatar answered Oct 03 '22 02:10

Mark Byers


An easy way to figure it out is to first write it as a query:

SELECT * FROM 
        table1 as t1 
        INNER JOIN  table2 as t2 on t1.id = t2.id
        INNER JOIN  table3 as t3 on t1.id=t3.id
        INNER JOIN  table4 as t4 on t1.id=t4.id
        WHERE  t1.username='%s' AND t1.id='%s'

If you get the results you expect, just replace the *Select ** with Delete and your table names. Then it would become:

Delete t1, t2, t3, t4 From table1 as t1 
        INNER JOIN  table2 as t2 on t1.id = t2.id
        INNER JOIN  table3 as t3 on t1.id=t3.id
        INNER JOIN  table4 as t4 on t1.id=t4.id
        WHERE  t1.username='%s' AND t1.id='%s'
like image 27
Jay Askren Avatar answered Oct 03 '22 02:10

Jay Askren