删除重复数据

 1、创建临时表

可以把数据先导入到一个临时表中,然后删除原表的数据,再把数据导回原表,SQL语句如下:
creat table tbl_tmp (select distinct* from tbl);
truncate table tbl;//清空表记录
insert into tbl select * from tbl_tmp;//将临时表中的数据插回来。

这种方法可以实现需求,但是很明显,对于一个千万级记录的表,这种方法很慢

2、rowid

delete from tbl where rowid in
(select a.rowid from tbl a, tbl b where a.rowid>b.rowid and a.col1=b.col1 and a.col2 = b.col2)

如果已经知道每条记录只有一条重复的,这个sql语句适用。
但是如果每条记录的重复记录有N条,这个N是未知的,就要考虑适用下面这种方法了。

3、max或min函数

这里也要使用rowid,与上面不同的是结合max或min函数来实现。SQL语句如下
delete from tbl a where rowid not in
(select max(b.rowid) from tbl b where a.col1=b.col1 and a.col2 = b.col2);//这里max使用min也可以

或者用下面的语句
delete from tbl a where rowid<(select max(b.rowid) from tbl b where a.col1=b.col1 and a.col2 = b.col2);
//这里如果把max换成min的话,前面的where子句中需要把"<"改为">"

只留有rowid最小的记录.
delete from people
where peopleId  in (select  peopleId  from people  group  by  peopleId   having  count(peopleId) > 1)
and rowid not in (select min(rowid) from  people  group by peopleId  having count(peopleId )>1)
跟上面的方法思路基本是一样的,不过使用了group by,减少了显性的比较条件,提高效率。
delete from tbl where rowid not in (select max(rowid) from tbl tg roup by t.col1, t.col2);
delete from tbl where (col1, col2) in (select col1,col2 from tbl group bycol1,col2 having count(*) >1)and
rowid not in(select min(rowid) from tbl group by col1,col2 having count(*) >1)

对于表中有重复记录的记录比较少的,并且有索引的情况:

delete from 表名 a where 字段1,字段2 in

  (select 字段1,字段2,count(*) from 表名 group by 字段1,字段2 having count(*) > 1)


这个网址也可以看看
http://tech.ccidnet.com/art/1107/20070403/1051589_1.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值