这是一个艰难的决定,
对于不同字段中的每个唯一值,如何删除除最后三行以外的所有行?
下面是问题的视觉效果:
id | otherfield
---------------
1 | apple <- DELETE
2 | banana <- KEEP
3 | apple <- DELETE
4 | apple <- KEEP
5 | carrot <- KEEP
6 | apple <- KEEP
7 | apple <- KEEP
8 | banana <- KEEP
我如何在sql中实现这一点?
最佳答案
未经测试,但这些方法可能会起作用:
DELETE t.*
FROM table t JOIN (
SELECT id
@rowNum := IF(@otherfield <> otherfield, 1, @rowNum + 1) rn,
@otherfield := otherfield otherfield
FROM (
SELECT id, otherfield
FROM table
ORDER BY otherfield, id DESC
) t, (SELECT @otherfield := NULL, @rowNum := -1) dm
) rs ON t.id = rs.id
WHERE rs.rn > 3
关于mysql - SQL删除除了每个唯一值的最后N行之外的所有行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4953409/