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

MySQL删除重复数据只保留一条

时间:2018-04-12 19:59:18      阅读:609      评论:0      收藏:0      [点我收藏+]

标签:rac   ora   date   net   AC   font   not   文章   sel   

 面试碰到一个MySQl的有趣的题目,如何从student表中删除重复名字的行,并保留最小id的记录?

很遗憾当时没有做出来,回家搜索了一番,发现利用子查询的可以很快解决。

1删除表中多余的重复记录,重复记录是username判断,只留有id最小的记录

delete from studentwhere
username in ( select username from studentgroup by username having count(username)>1)
and id not in (select min(id) as id from studentgroup by username having count(username)>1 )

(上面这条语句在mysql中执行会报错:

执行报错:1093 - You can‘t specify target table ‘student‘ for update in FROM clause

原因是:更新数据时使用了查询,而查询的数据又做了更新的条件,mysql不支持这种方式。oracel和msserver都支持这种方式。

怎么规避这个问题?

再加一层封装,

delete from student where
username in (select username from ( select username from student group by username having count(username)>1) a)
and id not in ( select id from (select min(id) as id from student group by username having count(username)>1 ) b)

 注意select min(id) 后面要有as id.

其实还有更简单的办法(针对单个字段):

delete from student where
id not in (select id from (select min(id) as id from student group by username) b);

 

拓展:

2、删除表中多余的重复记录(多个字段),只留有id最小的记录

delete from student a
where (a.username,a.seq) in (select username,seq from (select username,seq from a group by username,seq having count(*) > 1)  t1)
and id not in ( select id from (select min(id) from vitae group by username,seq having count(*)>1) t2)

参考文章:

https://blog.csdn.net/anya/article/details/6407280

MySQL删除重复数据只保留一条

标签:rac   ora   date   net   AC   font   not   文章   sel   

原文地址:https://www.cnblogs.com/shihuibei/p/8809908.html

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