【ORACLE】刪除表中重複資料

來源:互聯網
上載者:User

標籤:不能   ima   操作   基礎   有用   exp   group by   created   完全   

原因

在對資料庫進行操作過程中我們可能會遇到這種情況,表中的資料可能重複出現,使我們對資料庫的操作過程中帶來讀諸多不便,那麼怎麼刪除這些重複沒有用的資料呢?

平時工作中可能會遇到當試圖對庫表中的某一列或幾列建立唯一索引時,系統提示 ORA-01452 :不能建立唯一索引,發現重複記錄。

處理方法

重複的資料可能有這樣兩種情況:

第一種:刪除表中所有重複的資料

第二種:只保留重複資料中最新記錄的一條記錄【工作中常用】

 

重複資料刪除資料的想法

每一行資料所對應的rowid都是獨一無二的,及時表中兩個資料完全相同,rowid也是不同的。我們只需要找出重複值的ROWID就可以重複資料刪除值

 

 

類比資料  

[email protected]>Create table test as select * from emp;

[email protected]>insert into test select * from test;

-

[email protected]>insert into test select * from test;

28672 rows created.

Elapsed: 00:00:00.03

 

重複資料刪除值的所有資料

【方法一】

[email protected]>@?/rdbms/admin/utlexpt1.sql

產生exceptions表

向test表中加入(主鍵或是唯一約束)無法成功並把重複值rowid插入exceptions表中

[email protected]>alter table test add constraint test_empno_pk primary key(empno)

             exceptions into exceptions;

[email protected]>select count(*) from exceptions;

  COUNT(*)

----------

     28672

刪除全部重複資料

[email protected]>delete from test where rowid in (select row_id from exceptions);

28672 rows deleted.

Elapsed: 00:00:00.28

 

【方法二】

[email protected]>delete from test where ename in

( select ename from test group by ename having count(*)>2);

28672 rows deleted.

Elapsed: 00:00:00.34

【方法三】

方法三是建立在方法二的基礎上,由於測試資料比較少,我們無法考慮到資料庫大量資料的情況,大量刪除資料有可能造成會將資料庫弔死,所以我們可以將重複值插入到暫存資料表中,然後再對錶進行刪除

[email protected]>create table test_temp1

as (select empno,ename from test group by empno,ename having count(*)>2)

 

[email protected]>delete from test where (empno,ename) in (select empno,ename from test_temp1);

28672 rows deleted.

Elapsed: 00:00:00.26

 

 

重複資料刪除資料保留最新一條

也是利用rowid來對資料進行處理

[email protected]>delete from test where rowid not in (select max(rowid) from test group by ename);

28658 rows deleted.

Elapsed: 00:00:00.24

 

 

建立一個暫存資料表,向表中插入保留的rowid,

[email protected]>create table temp1(row_id urowid);

[email protected]>insert into temp1 select max(rowid) from test group by ename;

[email protected]>delete from test where rowid not in (select row_id from temp1);

28658 rows deleted.

Elapsed: 00:00:00.25

 

技術是分享,即是提升,也是創新,

文章如有錯誤,或者不同見解可以聯絡JAYEWU

1048586878 QQ:1048586878

 

【ORACLE】刪除表中重複資料

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.