求解exists子查询执行机制或原理问题

来源:互联网 发布:淘宝店虚拟产品货源 编辑:程序博客网 时间:2024/06/05 05:55

--测试数据
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)
--删除表
drop table tb

为什么这样写就可以得到A,B,C分组后每组里除了最小记录其它记录~这个子查询到底起了个什么作用。能不能大概模防一下他执行的过程或是原理什么的~我也知道上这个语句如果换成
select distinct * from tb a where not exists(select 1 from tb where F1=a.F1 and id<a.id)
就可以得到分组后每组的最小值,或是把“<”换成“>”号可以得到最大值,但就是想不出来为什么会得到这个值~

 

这样去理解就知道为什么了:

逐条扫描tb表, 每扫描一条记录, 去判断exists的查询是否会返回一个结果集
 如果会, 则这条记录保留, 否则这条记录不保留

exists中, a.f1, a.id 的值来源于当前被扫描到的记录.

 

原创粉丝点击