删除Oracle表中的重复行

来源:互联网 发布:linux smartctl 编辑:程序博客网 时间:2024/06/06 03:52

大概有两种方法:

方法1:基于rowid

delete from t a
where a.rowid !=
(
select max(b.rowid) from t b
where a.id = b.id and
a.col2 = b.col2
)

[c-sharp] view plaincopyprint?
  1. SQL> select * from t;  
  2.         ID COL2  
  3. ---------- --------------------------------  
  4.          1 a  
  5.          1 a  
  6.          2 b  
  7.          3 c  
  8. SQL> delete from t a where a.rowid != (select max(b.rowid) from t b where a.id=b.id and a.col2 = b.col2);  
  9. 已删除 1 行。  
  10. SQL> select * from t;  
  11.         ID COL2  
  12. ---------- --------------------------------  
  13.          1 a  
  14.          2 b  
  15.          3 c  

 

 

方法2:使用临时表

[c-sharp] view plaincopyprint?
  1. SQL> select * from t;  
  2.         ID COL2  
  3. ---------- --------------------------------  
  4.          1 a  
  5.          2 b  
  6.          3 c  
  7. SQL> insert into t values(1, 'a');  
  8. 已创建 1 行。  
  9. SQL> create table tt as select t.id, t.col2, max(t.rowid) dataid from t group by t.id, t.col2;  
  10. 表已创建。  
  11. SQL> delete from t a where a.rowid != (select b.dataid from tt b where a.id=b.id and a.col2=b.col2);  
  12. 已删除 1 行。  
  13. SQL> select * from t;  
  14.         ID COL2  
  15. ---------- --------------------------------  
  16.          2 b  
  17.          3 c  
  18.          1 a  

原创粉丝点击