MySql数据查重、去重的实现


一、单字段(nick_name)

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

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

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

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

3、查出多余的记录,不查出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);

4、删除多余的重复记录,只保留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)

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

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);

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

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

3、查出各个重复记录组中多余的记录数据,不查出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);

4、删除多余的重复记录,只保留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);
来源: 原创
标签: Mysql数据 查重 去重

作者介绍

Image Description

zfajax舫

小时候的梦想是当宇航员,长大的梦想是在北京买套90㎡房的小站长、自媒体人,2014年毕业,后从事过网站开发搭建工作;2016年,创建了张舫博客;20015-至今在北京工作(微信:a7983310)

评论列表

还没有人评论,抢占前排沙发

发表评论

关于作者

Image Description

zfajax舫

小时候的梦想是当宇航员,长大的梦想是在北京买套90㎡房的小站长、自媒体人,2014年毕业,后从事过网站开发搭建工作;2016年,创建了张舫博客;20015-至今在北京工作(微信:a7983310)

关注作者

Social Links

定制项目外包

Unit 25 Suite 3, 925 Prospect PI,
Beach Resort, 23001

手机号码

18600004319