“存在的地方”和索引

时间:2018-05-24 02:05:59

标签: sql sql-server sql-server-2008

下面的查询似乎没有使用在col1和col2上设置的索引。我不能期望包含“where exists”的SQL使用索引吗?

select a, b
from   [dbo].[test] testA
where exists 
    (
    select *
    from   [dbo].[test] as testB
    where  
    testA.col1 = testB.col1
    testA.col2 > testB.col2
    )   

1 个答案:

答案 0 :(得分:1)

您需要添加多列index

create index index_test_all on test ("col1","col2","a","b");

查询SQL:

select a, b
from   [dbo].[test] testA 
where exists (
  select 1
  from   [dbo].[test] as testB
  where  testA.col1 = testB.col1
    and testA.col2 > testB.col2
)   
;

执行计划:

DEMO SQL Fiddle