假设我们要删除每个用户的两个最新条目之外的所有条目......
CREATE TABLE my_table(itemid INT NOT NULL AUTO_INCREMENT PRIMARY KEY,userid INT NOT NULL);
INSERT INTO my_table VALUES
(1, 1),
(2, 1),
(3, 1),
(4, 3),
(5, 3),
(6, 3);
SELECT * FROM my_table;
+--------+--------+
| itemid | userid |
+--------+--------+
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 3 |
| 5 | 3 |
| 6 | 3 |
+--------+--------+
这是一个选择要删除的行的查询...
SELECT a.*
FROM my_table a
LEFT
JOIN
( SELECT x.*, COUNT(*) FROM my_table x JOIN my_table y ON y.userid = x.userid AND y.itemid >= x.itemid GROUP BY x.itemid HAVING COUNT(*) <=2)b
ON b.itemid = a.itemid
WHERE b.itemid IS NULL;
+--------+--------+
| itemid | userid |
+--------+--------+
| 1 | 1 |
| 4 | 3 |
+--------+--------+
...这是删除它们的查询...
DELETE a
FROM my_table a
LEFT
JOIN
( SELECT x.*, COUNT(*) FROM my_table x JOIN my_table y ON y.userid = x.userid AND y.itemid >= x.itemid GROUP BY x.itemid HAVING COUNT(*) <=2)b
ON b.itemid = a.itemid
WHERE b.itemid IS NULL;
SELECT * FROM my_table;
+--------+--------+
| itemid | userid |
+--------+--------+
| 2 | 1 |
| 3 | 1 |
| 5 | 3 |
| 6 | 3 |
+--------+--------+