1. 程式人生 > >一次成功批量刪除oracle冗餘資料的經歷

一次成功批量刪除oracle冗餘資料的經歷

問題描述:千辛萬苦往資料庫裡存了幾十萬條資料,發現由於程式問題,有將近10萬條的冗餘資料,此時內心是無比崩潰的,關於怎麼查詢是否有冗餘資料見上一篇文章(https://my.oschina.net/u/3636678/blog/2967373)。

嘗試1:首先想到的當然就是delete語句啦,如下所示:

sql = "delete from all_askrep a where (a.askname, a.atime) in (select askname,atime from all_askrep group by askname,atime having count(*)>1) and askrepid not in (select min(askrepid) from all_askrep group by askname,atime having count(*)>1)"
cursor.execute(sql)
conn.commit()

然後,發現一個小時後仍然沒結束,我就終止了操作,之後我加了一個rownum < 1000,先看看刪除前一千行資料需要的時間,發現也需要個二十分鐘,這有點過分啊!!

嘗試2:PL/sql方式執行,由於不太懂pl/sql語法,又急需對資料進行刪除操作,所以這次放棄了,相關例子可參考博文(https://www.cnblogs.com/nayitian/p/3238251.html

嘗試3:利用臨時表刪除資料,實踐證明這才符合我的需求,兩秒內執行完所有刪除操作。在嘗試第二種方法的時候安裝了plsqldev工具,藉助工具執行的刪除操作,當然了,不用工具是一樣的。程式碼如下(建立臨時表-》藉助臨時表刪除相關資料-》刪除臨時表):

create table tempaskrep as select a.askname, a.atime, a.askrepid as dataid from all_askrep a where a.askrepid not in (select max(b.askrepid) from all_askrep b group by b.askname,b.atime);
commit;
delete from all_askrep where askrepid in (select dataid from tempaskrep);
commit;
drop table tempaskrep;
commit;