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

时间:2011-02-10 04:33:21

标签: mysql sql sql-delete

这是一个艰难的, 对于不同字段中的每个唯一值,我如何删除除最后一行(比如说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中完成此操作?

2 个答案:

答案 0 :(得分:1)

未经测试,但这些内容可能有效:

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

答案 1 :(得分:1)

Delete MyTable
Where Id In (
            Select Id
            From    (
                    Select Id
                        , (Select COUNT(*)
                            From MyTable As T2
                            Where T2.OtherField = T.OtherField
                                And T2.Id > T.Id) As Rnk
                    From MyTable As T
                    ) As Z
            Where Z.Rnk > 2     
            )   

另一个可能更快一点的版本:

Delete MyTable
Where Id In (
            Select T.Id
            From MyTable As T
                Left Join MyTable As T2
                    On T2.OtherField = T.OtherField
                        And T2.Id > T.Id
            Group By T.Id
            Having Count(T2.Id) > 2
            )