我应该在我的sql server索引中添加主键吗?

时间:2015-08-10 15:09:30

标签: sql-server-2008-r2

我知道任何非聚集索引都包含主键。但我想知道它是否按特定顺序包含它。

我有一个查询,可以检索每个" MemberTee"最近的(最高身份证)和#34;会员身份"的teeID值。

SELECT
    MT.ID
    , MTH.teeID
FROM Favorite.tMemberTee AS MT
INNER JOIN (
    SELECT
        MTH.memberTeeID
        , MTH.teeID
        , ROW_NUMBER() OVER (PARTITION BY MTH.memberTeeID ORDER BY MTH.ID DESC) AS RNK
    FROM Favorite.tMemberTeeHist AS MTH
) AS MTH ON (
    MTH.memberTeeID = MT.ID
    AND
    MTH.RNK = 1
)

为了使此查询执行得最好,我需要一个由memberTeeID和ID(主键)排序的tMemberTeeHist索引。

以下是表DDL:

CREATE SCHEMA Favorite
GO

CREATE TABLE Favorite.tMemberTee (
    ID INT NOT NULL IDENTITY
    , CONSTRAINT PK_tMemberTee PRIMARY KEY (ID)

    , memberID BIGINT NOT NULL
    , CONSTRAINT FK_tMemberTee_memberID FOREIGN KEY (memberID) REFERENCES dbo.tMembers(ID)
    , courseID INT NOT NULL
    , CONSTRAINT FK_tMemberTee_courseID FOREIGN KEY (courseID) REFERENCES dbo.tCourseBases(ID) ON DELETE CASCADE
    , CONSTRAINT UQ_tMemberTee_01 UNIQUE (courseID, memberID)
)
GO

CREATE TABLE Favorite.tMemberTeeHist (
    ID INT NOT NULL IDENTITY
    , CONSTRAINT PK_tMemberTeeHist PRIMARY KEY (ID)

    , memberTeeID INT NOT NULL
    , CONSTRAINT FK_tMemberTeeHist_memberTeeID FOREIGN KEY (memberTeeID) REFERENCES Favorite.tMemberTee(ID) ON DELETE CASCADE
    , teeID INT NOT NULL
    , CONSTRAINT FK_tMemberTeeHist_teeID FOREIGN KEY (teeID) REFERENCES dbo.tTees(ID)

    , [date] DATETIME NOT NULL CONSTRAINT DF_tMemberTeeHist_date DEFAULT GETDATE()
    , originatorID INT NOT NULL
    , CONSTRAINT FK_tMemberTeeHist_originatorID FOREIGN KEY (originatorID) REFERENCES dbo.tClubMembers(ID)
)
GO

现在,我应该以这种方式创建索引(因为SQL SERVER内部已经在索引中订购了ID):

CREATE NONCLUSTERED INDEX IDX_tMemberTeeHist_memberTeeID ON Favorite.tMemberTeeHist (memberTeeID ASC) 
GO

或者我应该这样:

CREATE NONCLUSTERED INDEX IDX_tMemberTeeHist_memberTeeID ON Favorite.tMemberTeeHist (memberTeeID ASC, ID ASC) 
GO

1 个答案:

答案 0 :(得分:0)

由于约束

CONSTRAINT PK_tMemberTee PRIMARY KEY (ID)

创建默认的集群主键(因此是聚簇索引),该集群列ID 已经是每个非聚集索引的一部分(在叶级别)无论如何

再次单独添加它没有任何意义或没有益处。