去掉表里组合字段重复的记录

王朝other·作者佚名  2006-01-09
宽屏版  字体: |||超大  

当设计表的时候没有建组合字段唯一约束,以后需要增加这一约束时,却发现表里已经有了很多重复记录了。

请看看我用的去掉表里组合字段重复的记录方法:

假设原始表名为source_table,字段名1为field_name1,字段名2为field_name2。

(当然稍加修改也可以用到三个及以上组合字段重复的情况)

第一步: 生成组合字段重复的临时表source_dup_simple

create table source_dup_simple

nologging

pctfree 1 pctused 99

as select field_name1,field_name2,count(0) as num from source_table

group by field_name1,field_name2 having count(0)>1;

第二步: 生成组合字段重复的主表里完整记录的临时表source_dup

create table source_dup

nologging

pctfree 1 pctused 99

as select t1.* from source_table t1,source_dup_simple t2

where t1.field_name1=t2.field_name1 and t1.field_name2=t2.field_name2;

第三步: 删去source_dup里的重复记录

--可选择:保留rowid小的记录

delete from source_dup a where rowid > (

select min(rowid) from source_dup b where

a.field_name1 = b.field_name1 and a.field_name2=b.field_name2);

commit;

--可选择:保留rowid大的记录

delete from source_dup a where rowid < (

select max(rowid) from source_dup b where

a.field_name1 = b.field_name1 and a.field_name2=b.field_name2);

commit;

注意:如果操作一万条以上的记录最好在source_dup的field_name1和field_name2字段上建索引.

如果想按别的删除规则,如保留日期最新的记录:

--可选择:保留时间字段date_field大的记录

delete from source_dup a where date_field < (

select max(date_field) from source_dup b where

a.field_name1 = b.field_name1 and a.field_name2=b.field_name2);

commit;

--可选择:保留时间字段date_field小的记录

delete from source_dup a where date_field > (

select min(date_field) from source_dup b where

a.field_name1 = b.field_name1 and a.field_name2=b.field_name2);

commit;

如果时间字段上有重复,还需要再次根据rowid来删一次

delete from source_dup a where rowid < (

select max(rowid) from source_dup b where

a.field_name1 = b.field_name1 and a.field_name2=b.field_name2);

commit;

第四步: 删去所有重复组合字段原始表里记录

delete from source_table

where field_name1||field_name2 in (select field_name1||field_name2 from source_dup_simple);

commit;

注意:如果操作一万条以上的记录最好在source_table的field_name1和field_name2字段上建索引.

第五步: 把剩下的没有重复的记录插回原始表

insert into source_table select * from source_dup;

commit;

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有