为什么这是索引扫描而不是索引搜索

时间:2017-08-17 09:02:18

标签: sql sql-server sql-server-2014 query-performance sql-execution-plan

已在dw_assesment_detailsdw_assesment_details_id

上创建了聚簇索引
/* 6 minutes */
CREATE CLUSTERED INDEX [Ix_DW_ASSESSMENT_DETAILS_qid_QNO_TmpverName] 
ON [dbo].[DW_ASSESSMENT_DETAILS_QUESTION_ID]
(
    [TEMPLATENAME] ASC,
    [TEMPLATEVERSION] ASC,
    [QUESTION_NO] ASC
)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, 
      DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
GO

/* 9 minutes */
CREATE CLUSTERED INDEX [Ix_DW_ASSESSMENT_DETAILS_QNO_TmpverName] 
ON [dbo].[DW_ASSESSMENT_DETAILS]
(
    [TEMPLATENAME] ASC,
    [TEMPLATEVERSION] ASC,
    [QUESTION_NO] ASC
)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, 
      DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)

SELECT 
    [GETQUESTIONID], 
    dw.[TEMPLATENAME], dw.[TEMPLATEVERSION],
    dw.[QUESTION_NO]
FROM 
    [QIS_DW].[dbo].[DW_ASSESSMENT_DETAILS] dw 
INNER JOIN
    [QIS_DW].[dbo].[DW_ASSESSMENT_DETAILS_QUESTION_ID] id ON dw.TEMPLATENAME = id.TEMPLATENAME 
                                                          AND dw.TEMPLATEVERSION = id.TEMPLATEVERSION 
                                                          AND dw.QUESTION_NO = id.QUESTION_NO

但是上面的select查询是使用索引扫描 - 而不是索引搜索。如何使用索引寻求?

性能调优专家的任何建议?

enter image description here

2 个答案:

答案 0 :(得分:2)

  

如何使用索引查找?

如果您想尝试智能SQL Server优化器,可以指定LOOP JOIN查询提示。我希望MERGE JOIN的计划在很多行上表现得更好。

请注意,存储引擎还可能在大型扫描期间执行异步预读,以将数据预取到内存中,以便查询可以使用它,而无需等待从存储中读取。对于返回少量行的搜索,不会发生预读。

尝试以下查询,看看您的环境是否属于这种情况。

SET STATISTICS IO ON;
SET STATISTICS TIME ON;
GO

SELECT 
    [GETQUESTIONID], 
    dw.[TEMPLATENAME], dw.[TEMPLATEVERSION],
    dw.[QUESTION_NO]
FROM 
    [QIS_DW].[dbo].[DW_ASSESSMENT_DETAILS] dw 
INNER JOIN
    [QIS_DW].[dbo].[DW_ASSESSMENT_DETAILS_QUESTION_ID] id ON dw.TEMPLATENAME = id.TEMPLATENAME 
                                                          AND dw.TEMPLATEVERSION = id.TEMPLATEVERSION 
                                                          AND dw.QUESTION_NO = id.QUESTION_NO;
GO

SELECT 
    [GETQUESTIONID], 
    dw.[TEMPLATENAME], dw.[TEMPLATEVERSION],
    dw.[QUESTION_NO]
FROM 
    [QIS_DW].[dbo].[DW_ASSESSMENT_DETAILS] dw 
INNER JOIN
    [QIS_DW].[dbo].[DW_ASSESSMENT_DETAILS_QUESTION_ID] id ON dw.TEMPLATENAME = id.TEMPLATENAME 
                                                          AND dw.TEMPLATEVERSION = id.TEMPLATEVERSION 
                                                          AND dw.QUESTION_NO = id.QUESTION_NO
OPTION(LOOP JOIN);
GO

答案 1 :(得分:1)

在SQL Server中,Clustered或Non-Clustered索引表搜索更改索引扫描,直到我们没有在Where子句中添加条件。

Where子句会使Index寻求执行计划。 如果没有Where子句,它将作为索引扫描来搜索整个表数据。 这就是索引扫描总是很慢的原因。