熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> SQL語言 >> 正文

數據庫進階:刪除完全重復和部分關鍵字段重復的記錄

2013-11-13 12:37:18  來源: SQL語言 

  重復記錄分為兩種第一種是完全重復的記錄也就是所有字段均重復的記錄第二種是部分關鍵字段重復的記錄例如Name字段重復而其它字段不一定重復或都重復

  第一種重復很容易解決不同數據庫環境下方法相似

  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;

  發生這種重復的原因是由於表設計不周而產生的增加唯一索引列就可以解決此問題

  此類重復問題通常要求保留重復記錄中的第一條記錄操作方法如下 假設有重復的字段為NameAddress要求得到這兩個字段唯一的結果集

  Mysql
  alter table tableName add autoID int auto_increment not null;
  create table tmp select min(autoID) as autoID from tableName group by NameAddress;
  create table tmp select tableName* from tableNametmp where tableNameautoID = tmpautoID;
  drop table tableName;
  rename table tmp to tableName;
  SQL Server
  select identity(int) as autoID * into #Tmp from tableName;
  select min(autoID) as autoID into #Tmp from #Tmp group by NameAddress;
  drop table tableName;
  select * into tableName from #Tmp where autoID in(select autoID from #Tmp);
  drop table #Tmp;
  drop table #Tmp;
  Oracle
  DELETE FROM tableName t WHERE tROWID > (SELECT MIN(tROWID) FROM tableName t WHERE tName = tName and tAddress = tAddress);

  說明

   MySQL和SQL Server中最後一個select得到了NameAddress不重復的結果集(多了一個autoID字段在大家實際寫時可以寫在select子句中省去此列)

   因為MySQL和SQL Server沒有提供rowid機制所以需要通過一個autoID列來實現行的唯一性而利用Oracle的rowid處理就方便多了而且使用ROWID是最高效的刪除重復記錄方法


From:http://tw.wingwit.com/Article/program/SQL/201311/16259.html
    推薦文章
    Copyright © 2005-2013 電腦知識網 Computer Knowledge   All rights reserved.