Sql &引用;“存在的地方”;和索引
下面的查询似乎没有使用在col1和col2上设置的索引。难道我不能期望包含“where exists”的SQL使用索引吗Sql &引用;“存在的地方”;和索引,sql,sql-server,sql-server-2008,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 ) 对于此查
select a, b
from [dbo].[test] testA
where exists
(
select *
from [dbo].[test] as testB
where
testA.col1 = testB.col1
testA.col2 > testB.col2
)
对于此查询:
select a.a, a.b
from [dbo].[test] a
where exists (select 1
from [dbo].[test] a2
where a.col1 = a2.col1 and
a.col2 > b.col2
);
最好的索引是在测试(col1,col2)
上
我倾向于使用row\u number()
此版本假定col2
是唯一的。您可能需要rank()
而不是row\u number()
您需要添加多列索引
create index index_test_all on test ("col1","col2","a","b");
查询SQL:
执行计划:
@TimBiegeleisen看起来testA和testB是同一张表……感谢您的评论。是的,“testA”和“testB”都是“test”的别名。上面的查询非常简单,但基本上与真实的查询相同。请您共享测试表中的临时数据以及您需要的结果。谢谢Rajat。原始查询非常复杂,有几个datetime列用于“>”和几个int/varchar列用于“=”。谢谢!我认为“索引扫描”意味着查询不使用索引,这与“索引搜索”不同。如果我错了,请纠正我。谢谢戈登。两种我都试试。我甚至没有想过使用排名/排号。
create index index_test_all on test ("col1","col2","a","b");
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
)
;