2

从表 1 中删除 ConditionID=?ConditionID;

DELETE FROM Table2 WHERE ConditionID=?ConditionID;

DELETE FROM Table3 WHERE ConditionID=?ConditionID;

ConditionID 是 Table1、Table2、Table3 中存在的列,而不是单独运行 3 次,有没有办法在单个查询中运行所有三个(在 mysql 中)?

4

4 回答 4

6

如果ConditionID所有三个表都相同,则应该可以使用多表删除语法

DELETE Table1, Table2, Table3
FROM   Table1
JOIN   Table2 ON (Table2.ConditionID = Table1.ConditionID)
JOIN   Table3 ON (Table3.ConditionID = Table2.ConditionID)
WHERE  Table1.ConditionID = ?;

测试用例:

CREATE TABLE Table1 (id int, ConditionID int);
CREATE TABLE Table2 (id int, ConditionID int);
CREATE TABLE Table3 (id int, ConditionID int);

INSERT INTO Table1 VALUES (1, 100);
INSERT INTO Table1 VALUES (2, 100);
INSERT INTO Table1 VALUES (3, 200);

INSERT INTO Table2 VALUES (1, 100);
INSERT INTO Table2 VALUES (2, 200);
INSERT INTO Table2 VALUES (3, 300);

INSERT INTO Table3 VALUES (1, 100);
INSERT INTO Table3 VALUES (2, 100);
INSERT INTO Table3 VALUES (3, 100);

结果:

DELETE Table1, Table2, Table3
FROM   Table1
JOIN   Table2 ON (Table2.ConditionID = Table1.ConditionID)
JOIN   Table3 ON (Table3.ConditionID = Table2.ConditionID)
WHERE  Table1.ConditionID = 100;

SELECT * FROM Table1;
+------+-------------+
| id   | ConditionID |
+------+-------------+
|    3 |         200 |
+------+-------------+
1 row in set (0.00 sec)

SELECT * FROM Table2;
+------+-------------+
| id   | ConditionID |
+------+-------------+
|    2 |         200 |
|    3 |         300 |
+------+-------------+
2 rows in set (0.00 sec)

SELECT * FROM Table3;
Empty set (0.00 sec)
于 2010-09-17T23:45:37.550 回答
1

我不知道您的架构是什么样的,但是如果您使用 InnoDB 或类似的表引擎来处理您的表并且您有外键,您可以设置条件,在删除父条目时删除派生条目。有关详细信息,请参阅http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html

于 2010-09-17T23:42:15.283 回答
0

没有。ConditionID每一个都是独立的——仅仅因为它具有相同的名称并不意味着它是同一列。如果您完全限定名称,您将能够更好地看到它:

DELETE FROM Table1 WHERE Table1.ConditionID=?ConditionID;

DELETE FROM Table2 WHERE Table2.ConditionID=?ConditionID;

DELETE FROM Table3 WHERE Table3.ConditionID=?ConditionID;
于 2010-09-17T23:41:27.033 回答
0

您可以仅使用 mysql“删除”查询从多个表中删除行。考虑一下,您有两个表配置文件和书籍。

配置文件表包括,

  • ID
  • 姓名

书桌包括,

  • PID
  • 价格

您可以使用此查询从这两个表中删除特定 id 的记录,

delete profile,books from profile,books where profile.id=18 and profile.id=books.pid;
于 2011-10-12T11:01:09.147 回答