当前位置:首页 > 网络编程 > 数据库 > Mysql > 删除完全重复和部分关键字段重复的记录

删除完全重复和部分关键字段重复的记录

点击次数:34 次 发布日期:2008-11-22 09:06:23 作者:源代码网
源代码网推荐

源代码网整理以下重复记录分为两种,第一种是完全重复的记录,也就是所有字段均重复的记录,第二种是部分关键字段重复的记录,例如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是最高效的删除重复记录方法。

源代码网整理以下 

源代码网供稿.
网友评论 (0)
会员中心
网络编程
本站推荐
网络编程之精华