是否需要在非聚集索引中包含聚集索引列?


15

考虑到非聚集索引是基于聚集索引的,那么非聚集索引是否有必要列出聚集索引中包含的任何列?

换句话说,如果“产品”表在ProductID上包含聚集索引,则在创建非聚集索引时建议在其中包含ProductID列时,是否仍然需要将其添加为列?

如果不是,是否存在将列名添加到非聚集索引的好方案?

Answers:


20

在SQL Server中,总是将聚簇索引键列添加到非聚簇索引中以充当行定位器(请参阅:有关非聚簇索引键的更多信息)。

对于声明为唯一的NCI,将它们添加为包含列,否则将它们添加到密钥的末尾。

如果默认位置对于您的查询而言不是最佳的,则可能需要显式添加列。例如,如果要控制ASC/ DESC方向,或者要控制索引中键列的位置。

CREATE TABLE T
(
A INT,
B INT,
C INT ,
PRIMARY KEY CLUSTERED (B DESC, C DESC)
)

/*Implicitly adds B DESC, C DESC to end of key*/
CREATE NONCLUSTERED INDEX ix1 ON T(A ASC) 

/*No sort operation*/
SELECT  *
FROM T
ORDER BY A ASC,B DESC, C DESC

/*
But the avove index won't be able to seek into A,C  
and will need a residual predicate after seeking into A.

For the following query
*/

SELECT  *
FROM T
WHERE A=1 AND C > 4
ORDER BY C ASC, B DESC

/*This index explicitly controlling the key column position 
  and direction would be better*/
CREATE NONCLUSTERED INDEX ix2 ON T(A ASC, C ASC, B DESC) 
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.