之前的数据库去重一般会选择使用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
)
);