删除重复数据
看到的几种删除重复数据方法:总结下
test是需要处理的表有 m n两列
1 创建临时表
create table test_temp (select distinct * from test);
truncate table test
inserto into test (select * from test_temp);
适合小数据量
2 利用ROWID
因为数据库里的ROWID是唯一的
delete from test where rowid in (select a.rowid from test a,test b where a.rowid>b.rowid and a.m=b.m and a.n = b.n)
适合每条记录只有一条重复数据的情况
3 MAX或MIN函数(ROWID)
delete from test a where rowid not in (select max(b.rowid) from test b where a.m=b.m and a.n = b.n);
4 row_number函数
delete from test where rowid not in (select t.rowid from (select rowid,row_number() over (partition by m,n order by m,n) as rank from test) t where rank=1);
5 exceptions into exceptions
SQL> create table t ( a int, b int, c int );
表已创建。
SQL> insert into t select rownum,rownum+1,rownum+2 from all_objects where rownum <
<5;
已创建4行。
SQL> insert into t select *from t where rownum<<3;
已创建2行。
SQL> commit;
提交完成。
SQL> select *from t;
A B C
———- ———- ———-
1 2 3
2 3 4
3 4 5
4 5 6
1 2 3
2 3 4
已选择6行。
SQL> create table exceptions(row_id rowid,
2 owner varchar2(30),
3 table_name varchar2(30),
4 constraint varchar2(30));
表已创建。
SQL>
SQL> alter table t add constraint t_unique
2 unique(a,b,c) exceptions into exceptions;
alter table t add constraint t_unique
*
ERROR 位于第 1 行:
ORA-02299: 无法验证 (EPUSER.T_UNIQUE) - 未找到重复关键字
SQL> create table dups
2 as select *from t where rowid in (select row_id from exceptions);
表已创建。
SQL> select *from dups;
A B C
———- ———- ———-
1 2 3
2 3 4
1 2 3
2 3 4
SQL> select row_id from exceptions;
ROW_ID
——————
AAAIEJAAKAAAyMSAAA
AAAIEJAAKAAAyMSAAE
AAAIEJAAKAAAyMSAAB
AAAIEJAAKAAAyMSAAF
SQL> delete from t where rowid in ( select row_id
2 from exceptions );
已删除4行。
SQL> insert into t select distinct * from dups;
已创建2行。
SQL>
SQL> commit;
提交完成。
SQL> select *from t;
A B C
———- ———- ———-
3 4 5
4 5 6
1 2 3
2 3 4
查找重复数据:
SQL> select * from t a
2 where rowid >any (select rowid from t b where a.a=b.a);
A B C
———- ———- ———-
1 2 3
2 3 4
