資料庫刪除完全重複和部分關鍵字段重複的記錄

來源:互聯網
上載者:User

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是最高效的重複資料刪除記錄方法。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.