Delete duplicate rows from table

前端 未结 2 635
灰色年华
灰色年华 2021-01-15 13:59

I have unique keys id keys in my table but I have a column with duplicate values? how do I get rid of those, while preserving only one of them like this :

Duplicate

2条回答
  •  醉梦人生
    2021-01-15 14:45

    You can try this running multiple times:

    delete from mytable where id in (
        select max(id)
          from mytable
         group by name
        having count(1) > 1
    );
    

    Where multiple times equals the maximum number of repetitions you have in name column.

    Otherwise, you can try this more complex query:

    delete from mytable where id in (
        select id from mytable
        except 
        (
        select min(id)
          from mytable
         group by name
        having count(1) > 1
        union all
        select min(id)
          from mytable
         group by name
        having count(1) = 1
        )
    );
    

    Running this query one time only should delete all you need. Haven't tried it though...

提交回复
热议问题