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

所属分类: 数据库 / 数据库其它 阅读数: 105
收藏 0 赞 0 分享
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是最高效的删除重复记录方法。
更多精彩内容其他人还在看

ACCESS转SQLSERVER数据库的注意事项

Access承重量太低,当你考虑升级到SQL Server时,并不只是个连接字符串需要改变,需要改变的还有很多
收藏 0 赞 0 分享

数据库设计技巧[转]

数据库设计技巧[转]
收藏 0 赞 0 分享

iwms access与sql版的安装与转换

iwms access与sql版的安装与转换
收藏 0 赞 0 分享

[转载]让SQL运行得更快

笔者在工作实践中发现,不良的SQL往往来自于不恰当的索引设计、不充份的连接条件和不可优化的where子句。在对它们进行适当的优化后,其运行速度有了明显地提高!下面我将从这三个方面分别进行总结
收藏 0 赞 0 分享

[数据库] 通用分页存储过程第1/5页

[数据库] 通用分页存储过程
收藏 0 赞 0 分享

Access数据库升级为SQL数据库的注意事项和方法

Access数据库升级为SQL数据库的注意事项和方法
收藏 0 赞 0 分享

Win2003系统安装SQL Server2000后1433端口未开放的解释

这篇文章主要介绍了Win2003系统安装SQL Server2000后1433端口未开放的解释
收藏 0 赞 0 分享

SQL SERVER 与ACCESS、EXCEL的数据转换

SQL SERVER 与ACCESS、EXCEL的数据转换
收藏 0 赞 0 分享

Access转SqlServer的注意事项

Access转SqlServer的注意事项,需要的朋友可以参考下。
收藏 0 赞 0 分享

数据库的设计方法、规范与技巧

数据库的设计方法、规范与技巧
收藏 0 赞 0 分享
查看更多