码迷,mamicode.com
首页 > 数据库 > 详细

SQL去重

时间:2017-07-14 18:44:51      阅读:278      评论:0      收藏:0      [点我收藏+]

标签:select   where   重复数据   from   title   数据   主键   复数   分析   

现在有一张表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去重

标签:select   where   重复数据   from   title   数据   主键   复数   分析   

原文地址:http://www.cnblogs.com/againn/p/7171742.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!