单个查询中的多个删除
-
03-10-2019 - |
题
从table1删除prentionId =?条件;
DELETE FROM Table2 WHERE ConditionID=?ConditionID;
DELETE FROM Table3 WHERE ConditionID=?ConditionID;
条件ID是表1,Table2,Table3中存在的列,而不是单独运行3次,是否可以在单个查询中运行所有三个(在MySQL中)?
解决方案
如果是 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)
其他提示
我不知道您的模式是什么样的,但是如果您使用InnoDB或与外国钥匙相似的表引擎,则可以设置导致派生条目时删除父条目时删除的条件。看 http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-foreign-key-constraints.html 有关此信息的更多信息。
没有。 ConditionID
在每个中是分开的 - 只是因为它具有相同的名称并不意味着它是同一列。如果您完全符合名字的资格,您将能够更好地看到它:
DELETE FROM Table1 WHERE Table1.ConditionID=?ConditionID;
DELETE FROM Table2 WHERE Table2.ConditionID=?ConditionID;
DELETE FROM Table3 WHERE Table3.ConditionID=?ConditionID;
您只需使用MySQL“ delete” Query.consider,您就可以从多个表中删除行,这是两个表格配置文件和书籍。
个人资料表组成,
- ID
- 姓名
书桌组成,
- pid
- 书
- 价格
您可以通过使用此查询从这两个表中删除这两个表格的记录,
delete profile,books from profile,books where profile.id=18 and profile.id=books.pid;
不隶属于 StackOverflow