有两个意义上的重复记录,一是完全重复的记录,也即所有字段均重复的记录,二是部分关键字段重复的记录,比如Name字段重复,而其他字段不一定重复或都重复可以忽略。
1、 对于第一种重复,比较容易解决,而且方法类似:
I)Mysql
create table tmp select distinct * from tableName;
drop table tableName;
create table tableName select * from tmp;
drop table tmp;
II)SQL Server
select distinct * into #Tmp from tableName;
drop table tableName;
select * into tableName from #Tmp;
drop table #Tmp;
III)Oracle
create table tmp as select distinct * from tableName;
drop table tableName;
create table tableName as select * from tmp;
drop table tmp;
发生这种重复的原因是表设计不周产生的,增加唯一索引列即可解决。
2、 这类重复问题通常要求保留重复记录中的第一条记录,操作方法如下。 假设有重复的字段为Name,Address,要求得到这两个字段唯一的结果集
I)Mysql
alter table tableName add autoID int auto_increment not null;
create table tmp select min(autoID) as autoID from tableName group by Name,Address;
create table tmp2 select tableName.* from tableName,tmp where tableName.autoID = tmp.autoID;
drop table tableName;
rename table tmp2 to tableName;
II)SQL Server
select identity(int,1,1) as autoID, * into #Tmp from tableName;
select min(autoID) as autoID into #Tmp2 from #Tmp group by Name,Address;
drop table tableName;
select * into tableName from #Tmp where autoID in(select autoID from #Tmp2);
drop table #Tmp;
drop table #Tmp2;
III)Oracle
DELETE FROM tableName t1 WHERE t1.ROWID > (SELECT MIN(t2.ROWID) FROM tableName t2 WHERE t2.Name = t1.Name and t2.Address = t1.Address);
说明:
1. Mysql和SQL Server中最后一个select即得到了Name,Address不重复的结果集(但多了一个autoID字段,实际写时可以写在select子句中省去此列)
2. Mysql和SQL Server没有提供rowid机制,所以需要通过一个autoID列来实现行的唯一性,而利用Oracle的rowid处理就方便多了。而且也因为使用了ROWID,这也是最高效的删除重复记录方法。
--转自