SQL去重

Posted Againn

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQL去重相关的知识,希望对你有一定的参考价值。

现在有一张表t(id,name),id是主键,name可以重复,现在要删除重复数据,保留id最小的数据。请写出SQL。

表:t

id        name

1        张三

2        张三

3        李四

4        李四

5        李四

分析:

首先通过名字分组,选出每组id最小记录。然后删除这些记录以外的所有数据。

1:select min(id) id,name from t groud by name.

重点:min(),groud by, not exists()

完整的SQL:

 

delete from t a where not exists( select * from ( select min(id) ,name from t group by name) b where a.id=b.id)

 

 

 

以上是关于SQL去重的主要内容,如果未能解决你的问题,请参考以下文章