导航

关于Exists

Posted on 2006-06-05 17:18  Matildawaltzer  阅读(321)  评论(0编辑  收藏  举报
今天在csdn上看到这样一个问题。
create table tb(F1 varchar(10),id int)
insert tb select 'C',5
insert tb select 'A',1
insert tb select 'A',2
insert tb select 'B',1
insert tb select 'B',4
insert tb select 'B',7
insert tb select 'C',7
insert tb select 'C',5
--查询语句
select distinct * from tb a where exists(select 1 from tb where F1=a.F1 and id<a.id) 

搂主提问,exists起什么作用。
学习后总结。SQLServer的执行过程应该是:SQLServer将会一条一条的扫描tb表,每扫描一条记录就会判断exists的查询是否会返回一个数据集,
如果会返回数据集,则这条数据将会被保留,否则这条记录删除。

举一个例子:
求每个人的最好的成绩。
CREATE TABLE TBL_CJ
(
    no 
int , 
    name 
varchar(20) , 
    subject 
varchar(20), 
    score 
int
)
GO
insert into TBL_CJ
select 1'张三''语文'80 union   
select 2'李四''语文'83 union
select 3'王五''英语'99 union 
select 4'李四''数学'88 union   
select 5'张三''英语'66 union
select 6'王五''数学'87 union
select 7'李四''英语'69 union
select 8'张三''数学'63 union
select 9'王五''语文'77 
GO

注释:
每扫描一条数据就会判断一条,如果这一条中的成绩是最大的成绩,则"SELECT 1 FROM TBL_CJ  WHERE  M.[NAME] = [NAME] AND score > M.score"查不到数据,由于是Not Exists 所以这一条数据就会被保存。
如果查到有比这一条中的成绩还要大的数据,则"SELECT 1 FROM TBL_CJ  WHERE  M.[NAME] = [NAME] AND score > M.score" 就会有数据集,由于使用了Not Exists 则这条数据就会被删除。