mysql 存储去重_mysql去重之实战总结

一、有主键去重

a、单字段重复

676c06fb9942bf7711b5d7ef269e750e.png

查询重复记录(一条)

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

6421a1de01ffccecb16277797e6468e7.png

查询重复记录(全部)

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

f277a80c6a3fadfcd558833584fa99c5.png

删除重复记录保留一条

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,结果

47fd960dddc5ddb3ca639a97a5aeac40.png

于是经过查资料,sql整改

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

)

去重成功!

8c65805ca9108c1e9335ae82eb8b3a51.png

b、多字段重复

table ab

c9b668f69c8b4a850b999e830a6016d0.png

查询重复记录(一条)

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

cc8b55256c114b1e0c085ccbedc27ad0.png

查询重复记录(全部)

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

37a3458cfd7a1268d87f93cd17cbc6c7.png

删除重复记录保留一条

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

739118f42f3bea61b0a85a9c3128f8d2.png

删除重复记录保留一条

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

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;

32002121d3e20489ccb812899c382a10.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值