排查重复数据的几种方式:
(1)创建索引、主键、唯一约束排查.
create unique index idx_index_name on table_name(column_name1,column_name2);
此处的column_name为主键值,如果存在重复数据,
会报类似如下错误: ORA-01452: cannot CREATE UNIQUE INDEX; duplicate keys found;
例: table1: ( arg01, arg02, arg03 );
table2: ( arg01, arg02, arg03 );
如果要对比这俩个表中arg01、arg02、arg03都相同的数据,那么首先要查询单个表中是否有重复数据,可以分别在俩个表上创建唯一索引: create unique index idx_table1 on table1(arg01, arg02,arg03);
如果创建后出现类似的错误: ORA-01452: cannot CREATE UNIQUE INDEX; duplicate keys found; 说明表中存在重复数据,那么要确定重复数据的处理方式,接下来再去做以下的工作.
注:此处只以索引来举例,创建主键与唯一键实际上最终还是为了创建索引.
(2)group by: 还是以一中的例子来看,可以使用:
select arg01, arg02, arg03, count(*) as total from table1 group by arg01, arg02, arg03 having count(*) > 1;
查询出来的数据全部都是存在重复数据的. 获得表中唯一数据的方式:
(1)group by select arg01, arg02, arg02 from table1 group by arg01, arg02, arg03;
(2)distinct,如果一个表全部字段都作为比对数据,那么可以更方便的获得唯一数据.
select distinct * from table1;
删除多余数据的方式:
(1)delete from table1 t1 where t1.rowid not in (select max(rowid) from table1 t2 where t1.arg01 = t2.arg01 and t1.arg02 = t2.arg02 and t1.arg03 = t2.arg03);
(2)创建一个与table1一样的临时表. 首先把唯一数据查入临时表.
insert into temp_table1 select distinct * from table1(适用于全部字段都需要比对)
或者
insert into temp_table1 select arg01, arg02 from table1 group by arg01, arg02(适用部分字段比对);
然后删除主表所有数据,注意要使用delete,不要使用truncate,否则不能闪回: delete from table1;
接下来把临时表的数据插入到主表:
insert into table1 select * from temp_table1;
commit;