如何使用 SQL 根据 2 列的条件删除重复项

How to delete duplicates based on condition on 2 columns using SQL

我关注 table。我想删除重复的行并保留 Name1 = Name2 的行。因此,在下面的示例中,第 2 行和第 4 行应该被删除。

ID | Name1 | Name2
 1 | n1    |  n1
 1 | n1    |  n2
 2 | n1    |  n1
 2 | n1    |  n2

如何使用 SQL 查询执行此操作?

我认为这符合您的要求:

delete from t
    where t.name1 <> t.name2 and
          exists (select 1
                  from t t2 
                  where t2.id = t.id and
                        t2.name1 = t2.name2
                 );

如果您只想要一个 select,可以用类似的方式完成:

    select t.*
    from t
    where t.name1 = t.name2 or
          not exists (select 1
                      from t t2 
                      where t2.id = t.id and
                            t2.name1 = t2.name2
                     );