【发布时间】:2019-11-15 13:42:25
【问题描述】:
我有一张如下表
CREATE TABLE [dbo].[VideoRecipient](
[Id] [bigint] IDENTITY(1,1) NOT NULL,
[UserId] [int] NOT NULL,
[IssueId] [bigint] NOT NULL,
[CreatedDateTime] [datetime2](7) NOT NULL,
[NotifiedDateTime] [datetime2](7) NULL,
[ReceivedDateTime] [datetime2](7) NULL,
[ReadDateTime] [datetime2](7) NULL,
[AcknowledgedDateTime] [datetime2](7) NULL,
[IsDeleted] [bit] NOT NULL,
[DeletedDateTime] [datetime2](7) NULL,
CONSTRAINT [PK_VideoRecipient] PRIMARY KEY CLUSTERED
(
[Id] ASC
))
然后我创建一个索引如下
CREATE NONCLUSTERED INDEX UX_VideoRecipient_UserId_IssueId_CreatedDateTime ON [dbo].VideoRecipient ([UserId], [IssueId], [CreatedDateTime]) INCLUDE ([ReadDateTime], [ReceivedDateTime], [AcknowledgedDateTime], [NotifiedDateTime])
当我通过 UserId 进行查询以获取记录时,它使用索引并使用我想要的索引搜索。 如果我随后进行查询以通过 IssueId 获取记录,它会执行较慢的索引扫描。除了创建另一个索引并将 IssueId 指定为要索引的第一列之外,有没有办法使索引成为搜索而不是扫描?
指定要索引的第一列似乎比我最初想象的更重要!
【问题讨论】:
-
列顺序非常重要。 bertwagner.com/2018/09/04/…
-
想象你有一个电话簿(如果你知道这样的事情),它以
surname, first name的顺序列出了每个人的名字。使用该书查找名字为John的所有人。这本书使这项任务变得多么容易?
标签: sql sql-server indexing database-performance