如題,初探oracle刪除重復記錄,只保留rowid最小的記錄(rowid可以反映數據插入到數據庫中的順序)
一、刪除重復記錄可以使用多種方法,如下只是介紹了兩種方法(exist和in兩種)。
1.首先創建一個測試表。
create table my_users( id number, username varchar2(20), sal number )
2.插入測試數據
begin for i in 1..10 loop insert into my_users values(i,'carl_zhang',i+10); end loop; end; begin for i in 1..10 loop insert into my_users values(i,'carl_zhang',i+20); end loop; end; insert into my_users values(100,'carl',20.3); commit;
3.查看重復記錄
select rowid,rownum,a.* from my_users a where 1=1 and exists( select 'exist' from my_users b where 1=1 and a.id=b.id and a.username=b.username having count(*)>1 ) order by rowid
4.查看重復數據中,rowid最大的記錄(rowid可以反映數據插入到數據庫中的順序)
select rowid,rownum,a.* from my_users a where 1=1 and exists( select 'exist' from my_users b where 1=1 and a.id=b.id and a.username=b.username -- having count(*)>1 having count(*)>1 and a.rowid=max(b.rowid) ) order by rowid
5.刪除重復數據,保留rowid最小的記錄
delete from my_users a where 1=1 and exists( select 'exist' from my_users b where 1=1 and a.id=b.id and a.username=b.username -- having count(*)>1 having count(*)>1 and a.rowid=max(b.rowid) )
二、以上方法是通過exist實現,相比in、not in更加的快速。
1.如下,查看重復記錄。
select rowid,rownum,a.* from my_users a where 1=1 and (a.id,a.username) in( select b.id,b.username from my_users b where 1=1 having count(*)>1 group by b.id,b.username ) order by rowid
2.查看重復數據中,rowid最大的記錄
select rowid,rownum,a.* from my_users a where 1=1 and (a.id,a.username,rowid) in( select b.id,b.username,max(rowid) from my_users b where 1=1 having count(*)>1 group by b.id,b.username ) order by rowid
3.刪除重復數據,保留rowid最小的記錄
delete from my_users a where 1=1 and (a.id,a.username,rowid) in( select b.id,b.username,max(rowid) from my_users b where 1=1 having count(*)>1 group by b.id,b.username )