如何删除所有重复的行,包括SQL中的原始行?

时间:2019-03-15 11:24:26

标签: mysql sql phpmyadmin

我有一张这样的桌子:

id   id2
1    435  
2    345
3    345
4    567
5    456
6    987
7    987

id2中的345987在这里重复两次,因此我想删除这两行。我的新表应如下所示:

id   id2
1    435  
4    567
5    456

2 个答案:

答案 0 :(得分:4)

您可以使用聚合将其从select中删除:

select min(id), id2
from t
group by id2
having count(*) = 1;

如果要从表中删除它们,请使用joingroup by

delete t
    from t join
         (select id2, count(*) as cnt
          from t
          group by id2
         ) tt
         on t.id2 = tt.id2
    where cnt > 1;

答案 1 :(得分:0)

您可以使用not exists

select *
from table t
where not exists (select 1 from table t1 where t1.id2 = t.id2 and t1.id <> t.id);

同样,您可以删除记录:

delete t
from table t 
where exists (select 1 from table t1 where t1.id2 = t.id2 and t1.id <> t.id);