2014-02-14 158 views
0

什麼索引我有一個簡單的表:SQL Server創建

CREATE TABLE DocModHistory 
    [ID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL, 
    [DocID] [int] NOT NULL, 
    [BranchID] [int] NOT NULL, 
    [UserID] [int] NOT NULL, 
    [InsDate] [datetime] NOT NULL, 
    [Type] [int] NOT NULL, 
CONSTRAINT [PK_DocModHistory] PRIMARY KEY CLUSTERED 
(
[ID] ASC 
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,  ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] 
) ON [PRIMARY] 

和我有兩個選擇查詢:

SELECT dh.BranchID, MAX(dh.ID) as MaxID FROM DocModHistory dh WHERE dh.UserID = @p_UserID GROUP BY dh.BranchID 

SELECT dh.DocID, MAX(dh.ID) as MaxID FROM DocModHistory dh WHERE dh.UserID = @p_UserID GROUP BY dh.DocID 

你能告訴我請什麼我應該創建索引? 我應該爲UserID,BranchID,DocID創建單獨的索引,還是我需要多列索引?

謝謝!

回答

1

與包含的列BranchIDID和創建UserID指數DocID

因此,像

CREATE INDEX IX_UserID ON DocModHistory (UserID) INCLUDE (BranchID, ID ,DocID); 
+0

所以沒有必要創建兩個索引? SQL Server可以使用您建議的兩個查詢具有相同性能的索引嗎?謝謝! – Zsolt

+1

是的,它可以在兩個用戶ID都被過濾的情況下使用這兩個查詢,然後包含的列將被用作查詢的一部分,而不是密鑰查找。 –