我有一张这样的桌子:
id id2
1 435
2 345
3 345
4 567
5 456
6 987
7 987
id2
中的345
和987
在这里重复两次,因此我想删除这两行。我的新表应如下所示:
id id2
1 435
4 567
5 456
答案 0 :(得分:4)
您可以使用聚合将其从select
中删除:
select min(id), id2
from t
group by id2
having count(*) = 1;
如果要从表中删除它们,请使用join
和group 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);