select * from t a where exists
(select top 1 * from t b where a.id=b.id and a<=2000 order by A desc)这样写是多余的,因为本先一句就可以直接得到的结果,用了两个步骤,效率当然不高了!
如果必须的话,那么exists的效率好象要高于IN吧

解决方案 »

  1.   

    通常情况下,用exists()的查询比用in()的查询的效率高,但在楼主设置的这个场景下不具备可比性,楼主的查询可以替换成以下形式,效率不如TOP 1语句。select 
        a.* 
    from 
        t a 
    where 
        not exists(select 1 from t where id=a.id and A<=2000 and A>a.A)
      

  2.   

    应该是等价于如下语句:select 
        a.* 
    from 
        t a 
    where
        a.A<=2000
        and 
        not exists(select 1 from t where id=a.id and A<=2000 and A>a.A)
      

  3.   

    楼主为什么要转换成有exists 语句的?
      

  4.   

    libin_ftsafe(子陌红尘|潇湘剑公子@dev-club)两个SQL,我都执行了。结果都不对。:(
      

  5.   

    select 
        a.* 
    from 
        t a 
    where
        a.A<=2000
        and 
        not exists(select 1 from t where A<=2000 and A>a.A)
      

  6.   

    exists和in的效率基本相同,
    我覺得中間過程太多也影響效率。
      

  7.   

    如果就单单从,exists 与<=比的话,那一定是,exists效率高了,因为exists是对逻辑进行判断而<=是对每条记录的大小进行比较,效率当然就没有exists高了,楼主有兴趣的话可以看一下有关优化的文章,in,or,<=,>=,这些都是半优化的语句,而exists是全优化语句,还有楼主说的用exists怎么查询,对于楼主的这个问题如果用了,exists也不能提高多少效率因为,这个问题用exists写是这样的,select * from t a where not exists (select * from t where a.id=id and a>2000)这样写后可以说是用了,exists,可是它同时也用了子查询,而这同时也会影响查询的效率所以对于楼主这个问题,楼主用这两种办法都是差不多的
      

  8.   

    --表
    Create Table T(id int identity(1,1),A int, B datetime)
    insert into t select 1900,getdate()
    insert into t select 1900,getdate()
    insert into t select 1900,getdate()
    insert into t select 2015,getdate()
    insert into t select 1998,getdate()
    insert into t select 1999,getdate()
    insert into t select 2000,getdate()
    insert into t select 2001,getdate()
    insert into t select 2900,getdate()select 
        top 1 字段=A from T 
    where 
       A<=2000
    order by A desc select 
        字段=a.A 
    from 
        t a 
    where
        a.A<=2000
        and 
        not exists(select 1 from t where A<=2000 and A>a.A)drop table T
      

  9.   

    SELECT 字段=MAX(A)
    FROM T
    WHERE A<=2000倒排序的第一笔不就是MAX吗,干嘛搞那么复杂?
      

  10.   

    --Top  已经被优化的一个关键字,效率应该还是蛮高的.
    --子查询才会有 exits 的效率要比 in 的高的问题.
    --同意 libin_ftsafe(子陌红尘|潇湘剑公子@dev-club)