MySql数据库:数据查重、去重的实现

数据库的查重去重是java面试经常会被问到的问题,下面讲讲怎么实现这些,因为本人能力有限,所以只管实现,不考虑效率问题;

假设有一个表user,字段分别有id–nick_name–password–email–phone,分情况如下(注意删除多余记录时要创建临时表,不然会报错):

单字段(nick_name)

查出所有有重复记录的所有记录

select * from user where nick_name in
     (select nick_name from user group by nick_name having count(nick_name)>1);

查出有重复记录的各个记录组中id最大的记录

select * from user where id in (select max(id) from user group by nick_name having count(nick_name)>1);

查出多余的记录,不查出id最小的记录

select * from user where nick_name in

(select nick_name from user group by nick_name having count(nick_name)>1)

and id not in

(select min(id) from user group by nick_name having count(nick_name)>1);

删除多余的重复记录,只保留id最小的记录

delete from user where nick_name in
     (select nick_name from

(select nick_name from user group by nick_name having count(nick_name)>1) as tmp1)

and id not in

(select id from

(select min(id) from user group by nick_name having count(nick_name)>1) as tmp2);

多字段(nick_name,password)

查出所有有重复记录的记录

select * from user where (nick_name,password) in

(select nick_name,password from user group by nick_name,password where having count(nick_name)>1);

查出有重复记录的各个记录组中id最大的记录

select * from user where id in

(select max(id) from user group by nick_name,password where having count(nick_name)>1);

查出各个重复记录组中多余的记录数据,不查出id最小的一条

select * from user where (nick_name,password) in

(select nick_name,password from user group by nick_name,password having count(nick_name)>1)

and id not in

(select min(id) from user group by nick_name,password having count(nick_name)>1);

删除多余的重复记录,只保留id最小的记录

delete from user where (nick_name,password) in

(select nick_name,password from

(select nick_name,password from user group by nick_name,password having count(nick_name)>1) as tmp1)

and id not in

(select id from

(select min(id) id from user group by nick_name,password having count(nick_name)>1) as tmp2);

作者:zilie972803341
来源:CSDN
原文:https://blog.csdn.net/zilie972803341/article/details/78444703
版权声明:本文为博主原创文章,转载请附上博文链接!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值