我想你正在寻找这个:
DELETE FROM ranking WHERE id NOT IN (
SELECT id FROM ranking ORDER BY score DESC LIMIT 100);
这是说明这个概念的SQL Fiddle 。
它非常有效(事实上,它非常典型),因为嵌套查询只执行一次。它实际上更多地取决于“分数”是否被索引覆盖 - 与否:
(无索引):
EXPLAIN QUERY PLAN DELETE FROM ranking WHERE id NOT IN (
SELECT id FROM ranking AS ranking_subquery ORDER BY score DESC LIMIT 2);
--
selectid order from detail
0 0 0 SCAN TABLE ranking (~500000 rows)
0 0 0 EXECUTE LIST SUBQUERY 0
0 0 0 SCAN TABLE ranking AS ranking_subquery (~1000000 rows)
0 0 0 USE TEMP B-TREE FOR ORDER BY
(之后CREATE INDEX ts ON ranking(score);
)
selectid order from detail
0 0 0 SCAN TABLE ranking (~500000 rows)
0 0 0 EXECUTE LIST SUBQUERY 0
0 0 0 SCAN TABLE ranking AS ranking_subquery USING INDEX ts (~1000000 rows)