您的位置:首页 > 数据库

关于使用sql删除数据库重复的数据的方法整理:

2007-03-16 09:49 796 查看
关于使用sql删除数据库重复的数据的方法整理:

1.数据完全重复

通过一个临时表过渡一下
insert into table1 select distinct field from table
drop table table
insert into table select * from table1

2.某个字段重复

这个在网上有很多相关的解决方法,较常见的有
delete from table where id not in (select min(id) from table group by name)
delete from table where field in (select field from table group by field having count(*) > 1)

上面的方法在删除小数量级的数据时还有用,当一旦处理的数据是几十万或者更多时就出问题了,一般的机器估计一运行就马上给费了。其实稍有点常识的算一算就知道这样的语句会有多大的运算量了,它的运算量至少是以乘方的形式递增的,想想就恐怖。

我在这里主要是要给出对于大数量级的表的重复数据删除的解决方案,其实也很简单,也是利用了一个过渡表来实现
insert in tabletemp select * from table
delete from table as a where a.id > (select min(b.id) from table1 as b where b.field=a.field)
drop table tabletemp
这样利用了数据库的索引的优势,大大的减少运算量

========================================

SQL如何删除重复的数据行- -

delete from table where id in (
select max(id) from table group by name having count(*)>1
)--删除重复记录中ID最大的一条(如果有2条以上的重复记录则需多次执行)

如果table数据完全一样,可以先将数据导入到一个临时表内


delete from table where id not in (
select min(id) from table group by name
)--只保留重复记录的第一条(id最小的一条)

太少了..加点其它的内容

CREATE PROCEDURE 存储过程名 --执行动态SQL语句
(
@num int
)
AS
declare @string nvarchar(100)
set @string='SELECT TOP '+ CAST (@num as nvarchar) +' * FROM 表名'
exec (@string)

=====================================

select ID,NAME from house1 where name='中凯' and roomtype='双人间' and startdate>='2007-5-25' and id in(select min(id) from group by name)

name相同时id小的出现

======================

一般就是distinct , group by , #tempTable,

当然借助index会更快些
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: