场景:
a)假设现在数据库中有一个人员表(user),表中包括 主键ID,,姓名、身份证号码、等字段。
b) 由于程序的的原因、好来发现表中有许多理论上重复的数据(即姓名、和身份证号相同的数据), 现在需求是把这些重复的数据给删掉。
思路:
1) 通过 姓名和身份证号分组的sql去掉重复的数据。select Max(ID) as Id,姓名,身份证号 from User group by 姓名,身份证号, 得到得到一份没有重复姓名和身份证号的一组数据
2)我们只要得到没有重复数据的id就可以找出所有的并且不重复的数据了,使用嵌套的查询 得到所有的不重复数据的Id
select Id from (select Max(ID) as Id,姓名,身份证号 from User group by 姓名,身份证号) as t
3)然后使用临时表, 将不重复的数据放到临时表。 删除正式表的所有的数据, 然后将临时表的数据插入到正式表, 最后删除临时表。
a找出所有不重复的数据
select * into #temp1 from user where id in (select Id from (select Max(ID) as Id,姓名,身份证号 from User group by 姓名,身份证号) as t );
b,删除原表中的所有数据
delete from user;
c、将临时表中的数据在插入会user表
insert into user select * from #temp1;
d,删除临时表
drop #temp1;
关键点:
这里的关键是根据需要判断是否重复的字段分组后、使用聚合函数Max 或者Min得到唯一的ID,这一点十分重要。
具体的sql实现:
1.取出要留下的数据,本次依据重复项的最大id为保留项。
SELECT id,name,age from person
WHERE id in(
SELECT MAX(id) from person GROUP BY name,age
);
2.放入临时表
<pre name="code" class="sql">DROP TABLE IF EXISTS temp1;
CREATE TEMPORARY TABLE temp1 SELECT id,name,age from person
WHERE id in(
SELECT MAX(id) from person GROUP BY name,age
);
3.清空原表并从临时表注入
TRUNCATE person;
INSERT INTO person SELECT * from temp1;
DROP TABLE if EXISTS temp1;
SELECT * from person;
当然也可以直接delete:
DELETE from person WHERE id not in (
SELECT mid FROM(
SELECT MAX(id) mid from person GROUP BY name,age
) t
)
So do it,and change it,no regret!