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