Loading...

当前位置:资讯中心主页 >Mysql >文章内容

  • 删除完全重复和部分关键字段重复的记录
  • 来源:作者: 发布时间:2008-05-07 00:55:22
    • 域名注册

    • 域名惊喜价格 cn域名1元注册
    • com域名39.9

      虚拟主机

    • 主机按月支付,低至19元/月
    • 超大流量,可开子站点

      VPS主机

    • 特惠VPS168元/月,4-8M独享带宽保证
    • 独立操作系统,无限开站点

    重复记录分为两种,第一种是完全重复的记录,也就是所有字段均重复的记录,第二种是部分关键字段重复的记录,例如Name字段重复,而其他字段不一定重复或都重复。

    1、第一种重复非常容易解决,不同数据库环境下方法相似:

    以下为引用的内容:
    Mysql

    create table tmp select distinct * from tableName;

    drop table tableName;

    create table tableName select * from tmp;

    drop table tmp;


    SQL Server

    select distinct * into #Tmp from tableName;

    drop table tableName;

    select * into tableName from #Tmp;

    drop table #Tmp;

    Oracle

    create table tmp as select distinct * from tableName;

    drop table tableName;

    create table tableName as select * from tmp;

    drop table tmp;

    发生这种重复的原因是由于表设计不周而产生的,增加唯一索引列就能解决此问题。

    2、此类重复问题通常需求保留重复记录中的第一条记录,操作方法如下。 假设有重复的字段为Name,Address,需求得到这两个字段唯一的结果集

    Mysql

    以下为引用的内容:
    alter table tableName add autoID int auto_increment not null;

    create table tmp select min(autoID) as autoID from tableName group by Name,Address;

    create table tmp2 select tableName.* from tableName,tmp where tableName.autoID = tmp.autoID;

    drop table tableName;

    rename table tmp2 to tableName;

    SQL Server

    select identity(int,1,1) as autoID, * into #Tmp from tableName;

    select min(autoID) as autoID into #Tmp2 from #Tmp group by Name,Address;

    drop table tableName;

    select * into tableName from #Tmp where autoID in(select autoID from #Tmp2);

    drop table #Tmp;

    drop table #Tmp2;

    Oracle

    DELETE FROM tableName t1 WHERE t1.ROWID > (SELECT MIN(t2.ROWID) FROM tableName t2 WHERE t2.Name = t1.Name and t2.Address = t1.Address);

    说明:

    1. MySQL和SQL Server中最后一个select得到了Name,Address不重复的结果集(多了一个autoID字段,在大家实际写时能写在select子句中省去此列)

    2. 因为MySQL和SQL Server没有提供rowid机制,所以需要通过一个autoID列来实现行的唯一性,而利用Oracle的rowid处理就方便多了。而且使用ROWID是最高效的删除重复记录方法。

     


  • 以上内容由 华夏名网 搜集整理,如转载请注明原文出处,并保留这一部分内容。

      “华夏名网” http://www.sudu.cn 和 http://www.bigwww.com 是成都飞数科技有限公司的网络服务品牌,专业经营虚拟主机,域名注册,VPS,服务器租用业务。公司创建于2002年,经过6年的高速发展,“华夏名网”已经成为我国一家知名的互联网服务提供商,被国外权威机构webhosting.info评价为25大IDC服务商之一。

    华夏名网网址导航: 虚拟主机 双线主机 主机 域名注册 cn域名 域名 服务器租用 酷睿服务器 vps vps主机

  • (阅读次数:83)
  • 上一篇: 教你在MySQL中快速复制表格作为测试数据    下一篇: 全国主要城市的DNS服务器列表
  • [收藏] [推荐] [评论] [打印本页] [返回上一页][关闭窗口]
  • 昵称: (为空则显示guest)
  • 评论分数: ★ ★ ★★★ ★★★★ ★★★★★
  • 评论内容:(不能超过250字,需审核后才会公布,请自觉遵守互联网相关政策法规。