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

3

我有这样一个表:

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

在这里,id2345987重复出现了两次,因此我想删除这两行。我的新表应该是这样的:

id   id2
1    435  
4    567
5    456
2个回答

4
您可以通过聚合来从

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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接