DELETE FROM Table1 WHERE ConditionID =?ConditionID;
DELETE FROM Table2 WHERE ConditionID=?ConditionID;
DELETE FROM Table3 WHERE ConditionID=?ConditionID;
ConditionID是Table1,Table2,Table3中的一列,而不是单独运行3次,有没有办法在单个查询中运行所有这三个(在mysql中)?
答案 0 :(得分:4)
如果所有三个表的ConditionID
相同,您应该可以使用Multiple Table Delete Syntax:
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)
答案 1 :(得分:1)
我不知道您的架构是什么样的,但是如果您使用InnoDB或类似的表引擎并且您有外键,则可以设置条件,这些条件将导致在父条目时删除派生条目被删除。有关详细信息,请参阅http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html。
答案 2 :(得分:0)
不。 ConditionID
在每个中都是独立的 - 只是因为它具有相同的名称并不意味着它是同一列。如果您完全符合名称,您将能够更好地看到它:
DELETE FROM Table1 WHERE Table1.ConditionID=?ConditionID;
DELETE FROM Table2 WHERE Table2.ConditionID=?ConditionID;
DELETE FROM Table3 WHERE Table3.ConditionID=?ConditionID;
答案 3 :(得分:0)
您可以通过使用mysql“delete”query来删除多个表中的行。考虑到,您有两个表格配置文件和书籍。
个人资料表包含,
书籍表包含,
您可以使用此查询
从这两个表中删除特定ID的记录delete profile,books from profile,books where profile.id=18 and profile.id=books.pid;