中国IT动力,最新最全的IT技术教程
最新100篇 | 推荐100篇 | 专题100篇 | 排行榜 | 搜索 | 在线API文档 | 网通镜像
首 页 | 程序开发 | 操作系统 | 软件应用 | 图形图象 | 网络应用 | 精文荟萃 | 教育认证 | 硬件维护 | 未整理篇 | 站长教程
ASP JS PHP工程 ASP.NET 网站建设 UML J2EESUN .NET VC VB VFP 网络维护 数据库 DB2 SQL2000 Oracle Mysql
服务器 Win2000 Office C DreamWeaver FireWorks Flash PhotoShop 上网宝典 CorelDraw 协议大全 网络安全 微软认证
硬件维护  CPU  主板  硬盘  内存  显卡  显示器  键盘鼠标  声卡音箱  打印机  机箱电源  BIOS  网卡  C#  Java  Delphi  vs.net2005
  当前位置:> 程序开发 > Web开发 > JavaScripts > 综合文章
去掉表里组合字段重复的记录
作者:佚名 时间:2005-02-20 11:03 出处:互连网 责编:chinaitpower
              摘要:去掉表里组合字段重复的记录
当设计表的时候没有建组合字段唯一约束,以后需要增加这一约束时,却发现表里已经有了很多重复记录了。

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

假设原始表名为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;
关闭本页
 
首页 | 投资与合作 | 服务条款 | 隐私政策 | 收藏本站 | 设为首页 | 新用户注册 | 免责声明 | 使用帮助
Copyright ©2005-2008 chinaitpower.com All rights reserved. www.chinaitpower.com 版权所有