我在用户和角色之间有一个多对多连接表。
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必要的吗?