`
peachtao
  • 浏览: 37283 次
  • 性别: Icon_minigender_1
  • 来自: 湖南
文章分类
社区版块
存档分类

查询数据库中重复数据

阅读更多

查询数据库中重复数据

假如有这样一个表:
create table temp1
(
id int identity(1,1) primary key,
name varchar(100),
title varchar(100)
)

要删除temp1中name和title重复的数据,保留id号最大的那条,其它重复的删掉,这样的sql该如何写呢?
首先,找出重复的数据:
select id from temp1 a where exists
( select 1 from temp1 b where b.name =a.name and b.title =a.title and b.id<>a.id)
这样就找出了所有的重复数据id号,修改一下就能找出id号较小的重复数据了:


select id from temp1 a where exists
( select 1 from temp1 b where b.name =a.name and b.title =a.title and b.id>a.id)
仅仅将不等号变为>就实现了,找较大的则变为<。
这样要删除数据的id就出来了,删除就是很简单的事了:

delete temp1 where exists (select 1 from
(select id from temp1 a where exists
( select 1 from temp1 b where b.name =a.name and b.title =a.title and b.id>a.id)) c
where c.id=temp1.id)

看这样就完成了要求。个人认为not in 没有exists效率高,呵呵~尽管not in比exists方便一些,但还是坚持用exists。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics