我遇到了一种奇怪的情况,在选择列表中包含一个值将确定是否在查询中使用了我的索引。
我在cTable(cf1,cf2,cf3)上创建了一个索引。
在第一种情况下,对cTable执行表扫描:
select
a.bkey
,c.mappedvalue
from
aTable a
LEFT JOIN bTable b
ON b.bkey = a.bkey
LEFT JOIN cTable c ON (
c.[cf1] = b.[cf1] and
c.[cf2] = b.[cf2] and
c.[cf3] = a.[cf3]
)
;
但是,当我从选择列表中删除被映射的值列时,会使用索引:
select
a.bkey
--,c.mappedvalue
from
aTable a
LEFT JOIN bTable b
ON b.bkey = a.bkey
LEFT JOIN cTable c ON (
c.[cf1] = b.[cf1] and
c.[cf2] = b.[cf2] and
c.[cf3] = a.[cf3]
)
;
有人遇到过这个吗?优化程序只是在决定避免使用索引吗?
答案 0 :(得分:2)
删除列时,索引为covering index。
select
a.bkey
--,c.mappedvalue
from
aTable a
LEFT JOIN bTable b
ON b.bkey = a.bkey
LEFT JOIN cTable c ON (
c.[cf1] = b.[cf1] and
c.[cf2] = b.[cf2] and
c.[cf3] = a.[cf3]
)
;
您可以添加INCLUDE
:
CREATE INDEX idx ON cTable(cf1,cf2,cf3) INCLUDE (mappedvalue);
然后查询:
select
a.bkey
,c.mappedvalue
from
aTable a
LEFT JOIN bTable b
ON b.bkey = a.bkey
LEFT JOIN cTable c ON (
c.[cf1] = b.[cf1] and
c.[cf2] = b.[cf2] and
c.[cf3] = a.[cf3]
)
;
应使用索引idx
。