Nic*_*ico 15 sql-server-2005 sql-server-2008 nonclustered-index
考虑到非聚簇索引是基于聚簇索引的,非聚簇索引是否有必要列出聚簇索引中包含的任何列?
换句话说,如果 Products 表包含 ProductID 上的聚集索引,那么在创建非聚集索引时建议包含 ProductID 列时,是否有必要将其添加为列?
如果没有,是否有将列名添加到非聚集索引的情况?
Mar*_*ith 21
在 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)
Run Code Online (Sandbox Code Playgroud)