mysql实现去重的相关代码

之前的数据库去重一般会选择使用python的pandas,因为效率真的高也简单,不过作为练习,还是自己实现了一下使用sql语句实现的单表去重。

根据单字段实现去重
查出所有重复记录
select * from 表名 where 字段名 in 
(
	select 字段名 from 表名 
	group by 字段名 
	having count(字段名)>1
);
查出多余的记录,不查出id最小的记录
select * from 表名 where 字段名 in 
(
	select 字段名 from 表名
	group by 字段名
	having count(字段名) > 1
)
and id not in 
(
	select min(id) from 表名 
	group by 字段名
	having count(字段名) > 1
);
删除多余的重复记录,只保留id最小的记录
delete from 表名 where 字段 in (
	# 找出重复的post_id
	select 字段 from (
		select 字段 from 表名
		group by 字段
		having count(字段) >1
	) as temp_1
)
and id not in (
	# 剔除掉重复项里面id最小的记录
	select id from (
		select min(id) from 表名
		group by 字段名 having count(字段名) > 1
	) as temp_2
);

根据多字段内容去重
查出所有重复记录
select * from 表名
where (字段1, 字段2) in
(
	select 字段1, 字段2 from 表名
	group by 字段1, 字段2 
	having count(字段1) > 1
);
查出各个重复记录组中多余的记录,不包括重复项中id最小的那一条
select * from 表名
where (字段1, 字段2) in 
(
	select 字段1, 字段2 from 表名
	group by 字段1, 字段2
	having count(字段1) > 1
)
and id not in 
(
	select min(id) from 表名
	group by 字段1, 字段2
	having count(字段1) > 1
);
删除多余的重复记录,只保留id最小的记录
delete from 表名
where (字段1, 字段2) in 
(
	select 字段1, 字段2 from 表名
	group by 字段1, 字段2
	having count(字段1) > 1
)
and id not in 
(
	select id from 
	(
		select min(id) from 表名
		group by 字段1, 字段2
		having count(字段1) > 1
	)
);
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值