我已经多次看到这种情况,当我在 SQL Server 数据库引擎优化顾问中运行一些分析时,它建议我创建如下索引:
CREATE NONCLUSTERED INDEX [_index] ON [dbo].[SomeTable]
(
[Column1] ASC,
[Column2] ASC,
[Column3] ASC
)
INCLUDE ([PrimaryKeyColumn])
将主键(聚集索引)列包含到包含列列表中真的很重要吗?我始终认为它默认包含为原始行的链接。我错了吗?
更新: 我认为还需要注意的是,它为查询提出了这样的索引,例如: SELECT [PrimaryKeyColumn] FROM [dbo].[SomeTable] WHERE ...[条件]... 它确实影响绩效和执行计划。 据我了解,索引并不包含真正的“聚集索引”,而只是一些指向行的链接。是这样吗?
最佳答案
您可以使用或不使用 INCLUDE 创建索引:如果 PrimaryKeyCol 是聚集索引,SQL Server 将忽略它。也就是说,它不会存储两次聚集索引值
为了完整起见,如果我更改聚集索引,我可能会这样做
编辑:
我通过 size 观察到 SQL Server 会智能地处理这个问题
这并不像Kalen Delaney's More About Nonclustered Index Keys那么科学
DROP TABLE IncludeTest;
GO
CREATE TABLE IncludeTest (
BadClusteredKey uniqueidentifier DEFAULT NEWID() PRIMARY KEY,
OtherCol AS CHECKSUM(BadClusteredKey) % 10000,
Filler char(200) NOT NULL DEFAULT 'a and lots of spaces'
);
GO
INSERT IncludeTest (Filler) VALUES (DEFAULT);
GO
INSERT IncludeTest (Filler) SELECT Filler FROM IncludeTest
GO 20
SELECT COUNT(*) FROM IncludeTest;
EXEC sp_spaceused 'IncludeTest', 'true'
GO -- 400680 KB, 1920 KB
CREATE INDEX IX_OtherCol1 ON IncludeTest (OtherCol);
GO
EXEC sp_spaceused 'IncludeTest', 'true'
GO -- 400680 KB, 29024 KB KB
DROP INDEX IncludeTest.IX_OtherCol1
GO
EXEC sp_spaceused 'IncludeTest', 'true'
GO -- 400680 KB, 1920 KB
CREATE INDEX IX_OtherCol2 ON IncludeTest (OtherCol) INCLUDE (BadClusteredKey);
EXEC sp_spaceused 'IncludeTest', 'true'
GO -- 400680 KB, 29024 KB
DROP INDEX IncludeTest.IX_OtherCol2
GO
EXEC sp_spaceused 'IncludeTest', 'true'
GO -- 400680 KB, 1920 KB
关于sql-server - 为什么 SQL Server Tuning Advisor 建议将 PRIMARY KEY 添加到索引的包含列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9290367/