小编Ric*_*ard的帖子

复合主键 - 索引两个字段?

我在用户和角色之间有一个多对多连接表。

CREATE TABLE AppUserRole 
(
    UserId INT NOT NULL,
    RoleId INT NOT NULL, 

    CONSTRAINT PK_AppUserRole PRIMARY KEY (UserId, RoleId), 

    CONSTRAINT FK_AppUserRole_User FOREIGN KEY (UserId) 
        REFERENCES AppUser(UserId), 
    CONSTRAINT FK_AppUserRole_Role FOREIGN KEY (RoleId) 
        REFERENCES AppRole(RoleId)
);

CREATE INDEX IX_AppUserRole_RoleId ON AppUserRole(RoleId)
CREATE INDEX IX_AppUserRole_UserId ON User(UserId)
Run Code Online (Sandbox Code Playgroud)

既然复合键是按照 ( UserId, RoleId)的顺序聚集的,那么第二个索引 onUserId真的有必要吗?

当您查询特定的所有行时,UserId它将使用聚集索引。只有当您查询特定中的所有用户时,RoleId才会使用索引IX_AppUserRole_RoleId

索引是IX_AppUserRole_UserId必要的吗?

index sql-server learning primary-key t-sql

5
推荐指数
1
解决办法
1119
查看次数

标签 统计

index ×1

learning ×1

primary-key ×1

sql-server ×1

t-sql ×1