【发布时间】:2019-08-24 18:28:29
【问题描述】:
我有一个表,它在 ID 列上有一个主键/聚集索引,在系统日期列上有一个非聚集索引。如果我使用系统日期列查询表中的所有列(在这里覆盖索引没有意义),执行计划会显示一个键查找,因为对于它找到的每条记录,它必须使用 ID 来获取所有列数据。
奇怪的是,如果我用一个临时表编写 2 个查询,它的执行速度要快得多。我可以查询系统日期以获取 ID 表,然后使用该表搜索 ID 列。这是有道理的,因为您不再对每条记录进行慢键查找。
为什么优化器不为我们做这件事?
--slow version with key lookup
--id primary key/clustered index
--systemdate nonclustered index
select ID, col1, col2, col3, col4, col5, SystemDate
from MyTable
where SystemDate > '2019-01-01'
--faster version
--id primary key/clustered index
--systemdate nonclustered index
select ID, SystemDate
into #myTempTable
from MyTable
where SystemDate > '2019-01-01'
select t1.ID, t1.col1, t1.col2, t1.col3, t1.col4, t1.col5, t1.SystemDate
from MyTable t1
inner join #myTempTable t2
on t1.ID = t2.ID
【问题讨论】:
标签: sql sql-server query-optimization sql-tuning database-tuning