去掉表里組合字段重復(fù)的記錄
2024-07-21 02:33:23
供稿:網(wǎng)友
當(dāng)設(shè)計表的時候沒有建組合字段唯一約束,以后需要增加這一約束時,卻發(fā)現(xiàn)表里已經(jīng)有了很多重復(fù)記錄了。 請看看我用的去掉表里組合字段重復(fù)的記錄方法: 假設(shè)原始表名為source_table,字段名1為field_name1,字段名2為field_name2。 (當(dāng)然稍加修改也可以用到三個及以上組合字段重復(fù)的情況) 第一步: 生成組合字段重復(fù)的臨時表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;
第二步: 生成組合字段重復(fù)的主表里完整記錄的臨時表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里的重復(fù)記錄 --可選擇:保留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字段上建索引. 假如想按別的刪除規(guī)則,如保留日期最新的記錄: --可選擇:保留時間字段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; 假如時間字段上有重復(fù),還需要再次根據(jù)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; 第四步: 刪去所有重復(fù)組合字段原始表里記錄
delete from source_table
where field_name1field_name2 in (select field_name1field_name2 from source_dup_simple);
commit; 注重:假如操作一萬條以上的記錄最好在source_table的field_name1和field_name2字段上建索引. 第五步: 把剩下的沒有重復(fù)的記錄插回原始表
insert into source_table select * from source_dup;
commit;