mysql – SQL DELETE除了每个唯一值的最后N行之外的所有行

这是一个艰难的,

对于不同字段中的每个唯一值,我如何删除除最后一行之外的所有行,比如3行?

这是问题的视觉效果:

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
点赞