删除除两个以外的重复数据

时间:2017-04-17 23:04:10

标签: mysql

如何删除除两行之外的重复数据?

example

id 4必须删除,因为'mangga'已经有3行

1 个答案:

答案 0 :(得分:2)

这在MySQL中有点痛苦。以下标识要删除的行:

select t.*
from (select t.*,
             (@rn := if(@n = nama, @rn + 1,
                        if(@n := nama, 1, 1)
                       )
             ) as rn
      from t cross join
           (select @n := '', @rn := 0) params
      order by nama, id
     ) t
where rn > 2;

然后,您可以使用联接进行删除:

delete t
    from t join
         (select t.*,
                 (@rn := if(@n = nama, @rn + 1,
                            if(@n := nama, 1, 1)
                           )
                 ) as rn
          from t cross join
               (select @n := '', @rn := 0) params
          order by nama, id
         ) tt
         on t.id = tt.id
    where tt.rn > 2;