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)

 

 

 

posted @ 2017-07-14 17:58  Againn  阅读(5932)  评论(0编辑  收藏  举报