代码之家  ›  专栏  ›  技术社区  ›  Dmitry Adonin

从表中删除伪重复项

  •  1
  • Dmitry Adonin  · 技术社区  · 7 年前

    我有一个重复的表,只有一个字段不同,必须清理它们,看起来像:

    id1 | some_name    | some_details
    
    id2 | some_name    | some_details
    
    id3 | some_name    | some_details
    
    id4 | another_name | another_details
    
    id5 | another_name | another_details
    
    id6 | another_name | another_details
    

    ... 等。

    是否有人可以帮助您使用适当的SQL脚本来删除重复项并保留以下内容(例如):

    id1 | some_name    | some_details
    
    id4 | another_name | another_details
    

    1 回复  |  直到 7 年前
        1
  •  3
  •   jarlh    7 年前

    select ,只需做一个 GROUP BY ,使用 min() 要获取每个组的第一个id:

    select min(id), col2, col3
    from tablename
    group by col2, col3
    

    delete 不需要的行,只需 分组依据 最小() 要获取每个组的第一个id:

    delete from tablename t1
    where exists (select 1 from tablename t2
                  where t2.c2 = t1.c2 and t2.c3 = t1.c3
                    and t2.idcol < t1.idcol)
    

    即,如果存在具有相同col2和col3的另一行,但该行的id值较低,则删除该行。