在MySQL查询上需要一些帮助来删除userID计数大于1并且acl值= 4的行。
我作为选择查询尝试了什么:
DELETE FROM `users_acl`
WHERE userID IN(
SELECT * FROM `users_acl`
WHERE `acl` BETWEEN 2 AND 4
GROUP BY userID
HAVING COUNT(userID) > 1
);
但找不到合适的方法来删除同一查询中的行。
表格结构
+--------+-----+---------+
| userID | acl | deleted |
+--------+-----+---------+
| 27 | 2 | 0 |
| 28 | 2 | 0 |
| 31 | 2 | 0 |
| 42 | 2 | 0 |
| 42 | 4 | 0 |
| 45 | 1 | 0 |
| 51 | 1 | 0 |
| 54 | 1 | 0 |
| 63 | 2 | 0 |
| 63 | 4 | 0 |
| 64 | 1 | 0 |
| 69 | 2 | 0 |
| 73 | 2 | 0 |
| 73 | 4 | 0 |
| 76 | 1 | 0 |
| 77 | 2 | 0 |
| 77 | 4 | 0 |
+--------+-----+---------+
答案 0 :(得分:4)
在MySQL中,您无法同时从要删除的表格中进行选择。但是使用临时表可以解决这个问题
DELETE FROM `users_acl`
WHERE userID IN
(
SELECT * FROM
(
SELECT userID
FROM `users_acl`
GROUP BY userID
HAVING COUNT(userID) > 1
AND SUM(`acl` = 4) > 0
) tmp
);
或使用join
代替
DELETE u
FROM `users_acl` u
JOIN
(
SELECT userID
FROM `users_acl`
GROUP BY userID
HAVING COUNT(userID) > 1
AND SUM(`acl` = 4) > 0
) tmp on tmp.userID = u.userID