我有这个非聚集索引
CREATE NONCLUSTERED INDEX [nci_wi_StoreVariantInventory_F09B4BE817BC953FAC6861B7E46F6F51] ON [dbo].[StoreVariantInventory]
(
[ProductId] ASC,
[StoreId] ASC,
[VariantId] ASC
)
INCLUDE ( [LocalInventory]) WITH (STATISTICS_NORECOMPUTE = OFF, DROP_EXISTING = OFF, ONLINE = OFF) ON [PRIMARY]
GO
而这个聚集索引
ALTER TABLE [dbo].[StoreVariantInventory] ADD CONSTRAINT [PK_StoreVariantInventory] PRIMARY KEY CLUSTERED
(
[ProductId] ASC,
[ChainId] ASC,
[CountryCode] ASC,
[StoreId] ASC,
[VariantId] ASC
)WITH (STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF) ON [PRIMARY]
GO
为此表生成
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[StoreVariantInventory](
[ProductId] [bigint] NOT NULL,
[ChainId] [nvarchar](5) NOT NULL,
[CountryCode] [nvarchar](2) NOT NULL,
[StoreId] [bigint] NOT NULL,
[VariantId] [int] NOT NULL,
[Size] [int] NOT NULL,
[SizeRow] [nvarchar](1) NOT NULL,
[KoncernNumber] [nvarchar](4) NOT NULL,
[LocalInventory] [int] NOT NULL,
[OrderedInventory] [int] NOT NULL,
[Price] [money] NOT NULL,
[LastUpdated] [datetime] NOT NULL,
CONSTRAINT [PK_StoreVariantInventory] PRIMARY KEY CLUSTERED
(
[ProductId] ASC,
[ChainId] ASC,
[CountryCode] ASC,
[StoreId] ASC,
[VariantId] ASC
)WITH (STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[StoreVariantInventory] WITH CHECK ADD CONSTRAINT [FK_StoreVariantInventory_Stores] FOREIGN KEY([StoreId])
REFERENCES [dbo].[Stores] ([StoreId])
GO
ALTER TABLE [dbo].[StoreVariantInventory] CHECK CONSTRAINT [FK_StoreVariantInventory_Stores]
GO
ALTER TABLE [dbo].[StoreVariantInventory] WITH CHECK ADD CONSTRAINT [FK_StoreVariantInventory_Variants] FOREIGN KEY([ProductId], [VariantId])
REFERENCES [dbo].[Variants] ([ProductId], [VariantId])
GO
ALTER TABLE [dbo].[StoreVariantInventory] CHECK CONSTRAINT [FK_StoreVariantInventory_Variants]
GO
如果我做一个简单的选择
select LocalInventory
from StoreVariantInventory
where ProductId=1219100110
and VariantId = 49
and StoreId = 9050
and ChainId = 'F'
但是为什么它会选择非聚集索引呢?我正在做一个 100% 不适合非聚集索引的 WHERE 那么它如何使用它呢?当 WHERE 子句中的所有列都不是 100% 适合索引时,SQL Server 是否只是选择它看起来最合适的内容?没有像这里这样的索引不能 100% 适合我的 where 子句是不好的做法吗?
最初由i-one作为评论留下的答案:
您的查询引用了 ProductId、VariantId、StoreId、ChainId和LocalInventory列。
除ChainId外,所有这些都在非聚集索引定义中声明。
ChainId作为聚集索引键的一部分隐式包含在非聚集索引中。
所以,非聚集索引覆盖了这个查询。
非聚集索引包含聚集索引键,因为 SQL Server 必须能够从索引条目中找到基表行。
来自SQL Server 索引体系结构和设计指南: