--测试数据
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)
就可以得到分组后每组的最小值,或是把“<”换成“>”号可以得到最大值,但就是想不出来为什么会得到这个值~ 

解决方案 »

  1.   

    字面上理解吧。
    Exists  -->存在
      

  2.   

    这样去理解就知道为什么了:逐条扫描tb表, 每扫描一条记录, 去判断exists的查询是否会返回一个结果集
     如果会, 则这条记录保留, 否则这条记录不保留exists中, a.f1, a.id 的值来源于当前被扫描到的记录.
      

  3.   

    我理解的是这样:
    主查询应该先执行出这样的结果,把满足条件的查询出来
    select distinct * from tb a where F1=条件
    子查询也是根据这个条件,把满足条件的查询出来
    select * from tb where F1=条件
    然后把两个查询结果一一作比较,只要是存在id<a.id就返回
    不知道满足不满足求。
      

  4.   

    楼上正解逐条遍历所有记录,对每条记录都通过EXISTS中语句的返回值来判断是否保留在结果集中