資料庫刪除重複資料

2021-08-21 03:47:16 字數 1460 閱讀 3983

第一,資料庫中實體重複的解決方法。

實體重複也就是完全重複:即表中兩行記錄完全一樣的情況。這類資料重複就需要刪除一條記錄,解決方法比較簡單,具體操作如下:

使用select distinct * from tablename就可以得到無重覆記錄的結果集。

如果該錶需要刪除重複的記錄(重覆記錄保留1條),可以按以下方法刪除

select distinct * into #tmp from tablename

drop table tablename

select * into tablename from #tmp

drop table #tmp

發生這種重複的原因是表設計不周產生的,增加唯一索引列即可解決。

第二,資料庫中欄位重複的解決方法。

字段重複,這類重複問題通常要求保留重覆記錄中的第一條記錄,操作方法如下:

方法一:假設有重複的字段為name要求得到這個字段唯一的結果集

select identity(int,1,1) as autoid, * into #tmp from tablename

select min(autoid) as autoid into #tmp2 from #tmp group by name

select * from #tmp where autoid in(select autoid from #tmp2)

最後乙個select即得到了name不重複的結果集(但多了乙個autoid欄位,實際寫時可以寫在select子句中省去此列,如果要刪除庫里的重複資料,只要將對應的delectable或drop掉就可以了)。

方法二:保留重複資料中最新的一條記錄,操作方法如下:

在oracle中,rowid是隱藏字段,用來唯一標識每條記錄。所以,只要保留重複資料中rowid最大的一條記錄就可以了。  

查詢重複資料: 

select a.rowid,a.* from 表名 a 

where a.rowid != ( 

select max(b.rowid) from 表名 b 

where a.欄位1 = b.欄位1 and a.欄位2 = b.欄位2 );    

例:selete from dba_tables a 

where a.rowid!=( 

select max(rowid) from test b 

where a.owner=b.owner);

方法三:刪除重複資料,只保留最新的一條資料,操作方法如下:

delete from 表名 a 

where a.rowid != ( 

select max(b.rowid) from 表名 b 

where a.欄位1 = b.欄位1 and a.欄位2 = b.欄位2 )

刪除資料庫重複資料

上圖是資料庫定義,資料中儲存了97萬條資料。我要刪除其中的的重複資料,並保留其中一條。其中,如果merchantid,commodityid,price,pricetime 只看天數 相同的話,那麼就進行刪除。delete from history where merchantid,commodit...

關於資料庫重複資料的刪除

網上存在很多關於資料庫的資料查重的資料,由於專案的原因,網上找的並不是很合適 這裡記錄乙個我自己寫的刪除重複資料的語句.delete from a where id 唯一的鍵 in 後面的語句是選擇重複的資料的id select id from select row number over part...

Oracle 資料庫刪除完全重複資料

oracle minus 關鍵字 sql中的minus關鍵字 sql中有乙個minus關鍵字,它運用在兩個sql語句上,簡單來說,就是找到第乙個sql語句的結果中有且 第二個sql語句結果中沒有的記錄,其語法如下 sql segment 1 minus sql segment 2 刪除完全重覆記錄 ...