为什么在此查询中不使用聚簇索引?

时间:2013-03-07 20:38:03

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

我有下表:

CREATE TABLE [Cache].[Marker](
    [ID] [int] NOT NULL,
    [SubID] [varchar](15) NOT NULL,
    [ReadTime] [datetime] NOT NULL,
    [EquipmentID] [varchar](25) NULL,
    [Sequence] [int] NULL
) ON [PRIMARY]

使用以下聚集索引:

CREATE UNIQUE CLUSTERED INDEX [IX_Marker_EquipmentID_ReadTime_SubID] ON [Cache].[Marker] 
(
    [EquipmentID] ASC,
    [ReadTime] ASC,
    [SubID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO

这个查询:

Declare @EquipmentId nvarchar(50)

Set @EquipmentId = 'KLM52B-MARKER'

SELECT TOP 1 
    cr.C44DistId,
    cr.C473RightLotId
From Cache.Marker m
    INNER JOIN Cache.vwCoaterRecipe AS cr ON cr.MarkerId = m.ID
Where m.EquipmentID = @EquipmentId And m.ReadTime >= '3/1/2013'
ORDER BY m.Id desc  

以下是正在生成的查询计划:

enter image description here

我的问题是这个。为什么Cache.Marker表上的聚集索引不与搜索一起使用而不是另一个索引上的扫描?此外,SSMS查询分析器建议我在Marker.ReadTime上添加索引,其中包含ID和EquipmentID列。

Cache.Marker表中大概有1M行。

1 个答案:

答案 0 :(得分:3)

您有多少独特的设备ID?它可能决定日期是更好的第一次查找(可能是错误的)。您可以使用WITH( INDEX() )语句强制它使用索引。 FORCESEEK也可以提供帮助。我强烈推荐这个,因为随着数据库增长到大尺寸,索引行为是可预测的。

SELECT TOP 1 
    cr.C44DistId,
    cr.C473RightLotId
From Cache.Marker m
     WITH ( INDEX( IX_Marker_EquipmentID_ReadTime_SubID ), FORCESEEK )
    INNER JOIN Cache.vwCoaterRecipe AS cr 
    ON cr.MarkerId = m.ID
Where m.EquipmentID = @EquipmentId And m.ReadTime >= '3/1/2013'
ORDER BY m.Id desc