1、第一種重復很容易解決,不同數據庫環境下方法相似:
以下為引用的內容:
Mysql
create table tmp select distinct * from tableName;
drop table tableName;
create table tableName select * from tmp;
drop table tmp;
SQL Server
select distinct * into #Tmp from tableName;
drop table tableName;
select * into tableName from #Tmp;
drop table #Tmp;
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,要求得到這兩個字段唯一的結果集
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;
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;
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是最高效的刪除重復記錄方法。