最近在公司实习的时候,遇到:
由于某些原因,一张表中存在重复的记录:
主要字段的值相同(如:name,age,birthday),而其它非主要字段(如:自增序号id)。
现在要删除重复的记录(重复记录只保留一条),做法如下:
假设当时的创建表语句为:
create table person(
id int(5) autoincrement,
name varchar(20),
age int(3)
);
现在表中存在重复记录,比如:
现在要只保留一条记录。
id | name | age |
3 | csdn | 23 |
6 | csdn | 23 |
实现代码如下:
#删除临时表
drop table if exists temp_p,temp_p2,temp_repeat_ids;
#创建三张临时表
create temporary table temp_p select * from person;
create temporary table temp_p2 select * from person;
create temporary table temp_repeat_ids (
(select p1.id
from temp_p p1
where p1.id in(
select repeats.id_p2 from (
select p2.id as id_p2,count(p2.name) as name_repeats
from temp_p2 p2
group by p2.id
) repeats
where repeats.name_repeats>1
) group by p1.id
);
#删除重复数据
set SQL_SAFE_UPDATES = 0;
delete from person p
where p.id in (select * from temp_repeat_ids);
set SQL_SAFE_UPDATES = 1;
##以上代码全部运行一次,会把当前数据库中重复n次的记录(n>=2),删除一次。
##如果有记录重复了3次,则要运行上面代码2次。当然如果多运行几次,也不会把只出现一次的记录删除(此时运行100次和运行2次的效果一样)。