MySQL的删除多个表行MySQL的删除多个表行(MySQL delete row from mul

2019-05-12 03:52发布

这是做了正确的方法是什么?

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'

Answer 1:

对,那是正确的。 在这里工作得很好:

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

如果它不为你工作,也许你可以修改这个例子来说明您有什么问题。



Answer 2:

一个简单的方法来弄明白是先写一个查询:

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'

如果你得到你所期望的结果,只需更换*选择**与删除和你的表名。 然后,它会变成:

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'


Answer 3:

使简单用:

DELETE FROM `Table1` t1, `Table2` t2 USING t1, t2
WHERE t1.`id` =  t2.`id` AND t1.`id` = 10; <br>

请享用 :)



文章来源: MySQL delete row from multiple tables