create table test (deptNo nvarchar(10), proName nvarchar(10),  time nvarchar(10),  num int )
insert test 
select 'a'  ,    'book'  ,  5   ,33  union allselect 'a'  ,    'book'  ,  6   ,44 union allselect'a'  ,    'book'  ,  7   ,55 union allselect 'b'  ,    'book'  ,  5   ,33  union allselect 'b'  ,    'book'  ,  5   ,33  union allselect 'b' ,    'book'  ,  7   ,55 select * from testselect * from test as a  where exists 
(select * from test where time>'5' or time>'6'or time>'7')select * from test as a where exists 
(select * from test where time>a.time)

解决方案 »

  1.   

    1:第二次的条件也是为真,为什么结果和第一次的不一样
    2:即使取了交集,那返回的也应该是2,3,5,6这4条记录吧
    3:第二句的time>a.time难道不等于第一句的time>'5' or time>'6'or time>'7'吗我想楼主没有真正理解 exists 用法。exists 查询,首先从外层查询中找记录,此时查看内层查询条件是否满足。如果满足则将次外层记录插入结果表中。select * from test as a  where exists (select * from test where time>'5' or time>'6'or time>'7'),这这个查询中,首先 会在外层查询select * from test as a 中找到这条记录, a      book    5   33,此时内层查询条件select * from test where time>'5' or time>'6'or time>'7'显然满足,返回真,次记录插入结果表中输出,然后查找第二条记录,依次扫描全表。在下面查询中select * from test as a where exists 
    (select * from test where time>a.time) ,外层查到a      book    7   55,这条记录时,内查询条件不满足,所以不输入到结果表中。也没有内查询中不存在比7大的。条件返回FALSE。
      

  2.   

    laoliu666 
    麻烦问一下
    难道time>'5' or time>'6'or time>'7'不等于time>a.time 吗
    如果不等
    那time>a.time 要做何解呢
      

  3.   

    显然不等。可以简单这样理解exists。请看select * from test as a where exists 
    (select * from test where time>a.time)句.首先你要明白查询结果来自外层查询,内层只做判断用。 在外层中 test 表你已经定义了个别名a,首先逐条记录扫描表a, 可以设想有指针指向a表中 第一条记录,a      book    5   33,此时判断内层查询是否为真,select * from test where time>a.time,这有个自连接。这时扫描整个 test表,把time>5的记录选出,显然这样的记录是存在的。所以内查询返回TRUE,因此a表中第一条记录插入结果表中。然后a表指针指向第二条记录,同样办法判断内查询返回值。 当扫描到a表第三条记录时,a表中time直为7,此时,内查询 select * from test where time>7 ,查询不到结果,所以返回直为false.所以结果中你可以看到是两TIME为7的没有显示。而select * from test as a  where exists 
    (select * from test where time>'5' or time>'6'or time>'7')这个查询中,内查询恒为TRUE。所以返回全表。