mysql去重

https://www.cnblogs.com/rocky404/p/6734958.html

一、有主键去重

a、单字段重复

 

table  ab

查询重复记录(一条)

1

select aid from ab group by aid having count(*)>1

result:

 查询重复记录(全部)

1

select from ab t where t.aid in(select aid from ab group by aid having count(*)>1);

result:

  删除重复记录保留一条

1

2

3

4

5

delete from ab where aid in(

  select aid from ab group by aid having count(*)>1

)and id not in(

  select max(id)as id from ab group by aid having count(*)>1

)

刚开始想到这个sql,结果

 于是经过查资料,sql整改

1

2

3

4

5

6

7

8

9

delete from ab where aid in(

    select t.aid from(

        select aid from ab group by aid having count(*)>1

    ) t

)and id not in(

    select t.id from(

        select max(id) as id from ab group by aid having count(*)>1

    ) t

)

 

 去重成功!

 

 b、多字段重复

table  ab

 查询重复记录(一条)

1

select aid,bid from ab group by aid,bid having count(*)>1

result:

  查询重复记录(全部)

1

select from ab t where(t.aid,t.bid)in(select aid,bid from ab group by aid,bid having count(*)>1);

result:

 删除重复记录保留一条

1

2

3

4

5

6

7

8

9

delete from ab where (aid,bid) in (

    select t.aid,t.bid from (

        select aid,bid from ab group by aid,bid having count(*)>1

    ) t

and id not in (

    select t.id from (

        select max(id) as id from ab group by aid,bid having count(*)>1

    ) t

)

去重成功!

 

二、无主键去重

单字段、多字段

table ab

 

 删除重复记录保留一条

1

2

3

4

5

6

7

8

9

10

11

12

--建临时表插入去重数据

create table ab_temp (select from ab group by aid,bid having count(*)>1);

--删除重复数据

delete from ab where (aid,bid) in (

    select t.aid,t.bid from (

        select aid,bid from ab group by aid,bid having count(*)>1

    ) t

);

--插入去重数据

insert into ab select from ab_temp;

--删除临时表

drop table ab_temp;

 去重成功!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值