从多个表中删除行

时间:2014-02-11 13:45:30

标签: mysql sql

我想删除多个表中的行,我该怎么做? 我试过了

DELETE a.*, b.*, c.*
FROM table1 as a, table2 as b, table3 as c
WHERE a.colName = 'value'
AND b.colName = 'value'
AND a.c.colName = 'value';

'value'对于所有表格以及colName都是相同的。

对于此查询,记录必须存在于所有表中,但在我的情况下,表中可能存在也可能不存在记录。 当我们运行删除查询时,它会删除现有记录,否则返回'0 row(s) affected'。所以我只想运行3个这样的查询

DELETE FROM table1 WHERE colName = 'value';
DELETE FROM table1 WHERE colName = 'value';
DELETE FROM table1 WHERE colName = 'value';

在一个查询中。

由于

4 个答案:

答案 0 :(得分:1)

因为您的实际问题是一次执行多个查询。最好的解决方案是集成mysqli扩展并使用mysqli_multi_query()与这些查询:

DELETE FROM table1 WHERE colName = 'value';
DELETE FROM table2 WHERE colName = 'value';
DELETE FROM table3 WHERE colName = 'value';

答案 1 :(得分:1)

使用连接删除在mysql中有点奇怪。你需要这样的东西:

编辑:

允许所有表中不存在的行

DELETE FROM 
  table1, table2, table3
USING 
  table1 
LEFT JOIN 
  table2 ON table2.colName = table1.colName 
LEFT JOIN 
  table3 ON table3.colName = table1.colName 
WHERE 
  table1.colName = 'value'

答案 2 :(得分:1)

考虑以下内容......

DROP TABLE IF EXISTS table1;

CREATE TABLE table1
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,colname CHAR(1) NOT NULL
);

DROP TABLE IF EXISTS table2;

CREATE TABLE table2
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,colname CHAR(1) NOT NULL
);

DROP TABLE IF EXISTS table3;

CREATE TABLE table3
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,colname CHAR(1) NOT NULL
);

INSERT INTO table1 (colname) VALUES ('x'),('y'),('z');

INSERT INTO table2 (colname) VALUES ('x'),('x'),('z');

INSERT INTO table3 (colname) VALUES ('y'),('y'),('z');

SELECT * FROM table1;
  +----+---------+
  | id | colname |
  +----+---------+
  |  1 | x       |
  |  2 | y       |
  |  3 | z       |
  +----+---------+

SELECT * FROM table2;
  +----+---------+
  | id | colname |
  +----+---------+
  |  1 | x       |
  |  2 | x       |
  |  3 | z       |
  +----+---------+

SELECT * FROM table3;
  +----+---------+
  | id | colname |
  +----+---------+
  |  1 | y       |
  |  2 | y       |
  |  3 | z       |
  +----+---------+

DELETE a, b, c
  FROM table1 a
  JOIN table2 b
    ON b.colname = a.colname
  JOIN table3 c
    ON c.colname = a.colname
 WHERE a.colName IN('x','z');

SELECT * FROM table1;
  +----+---------+
  | id | colname |
  +----+---------+
  |  1 | x       |
  |  2 | y       |
  +----+---------+

SELECT * FROM table2;
  +----+---------+
  | id | colname |
  +----+---------+
  |  1 | x       |
  |  2 | x       |
  +----+---------+

SELECT * FROM table3;
  +----+---------+
  | id | colname |
  +----+---------+
  |  1 | y       |
  |  2 | y       |
  +----+---------+ 

正如迈克已经证明的那样,你可以用INNER JOIN代替OUTER JOIN来完全删除'x'值,尽管它们不在table3中

答案 3 :(得分:0)

我建议设置一个收集所有行的视图,然后从该视图中删除。

CREATE VIEW v AS
SELECT colName FROM a
UNION ALL
SELECT colName FROM b
UNION ALL
SELECT colName FROM c

然后

DELETE FROM v
WHERE colName = 'value'