Ric*_*ard 5 index sql-server learning primary-key t-sql
我在用户和角色之间有一个多对多连接表。
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必要的吗?
查询按列顺序使用索引(先是 UserId,然后是 RoleId)。如果 RoleId 上没有索引,它将扫描聚集索引。除非有带有 userId 的 where 子句,否则引擎不知道如何在不扫描所有 userId 的情况下进入索引。
由于 roleId 是一个 FK,因此最佳实践建议对其建立索引。如果您(经常)查询它,您肯定需要它。
仅针对 UserId 建立索引是没有用的。由于 UserId 是入口点,聚集索引已经做到了这一点。使用它不需要额外查找 PK 来获取数据或关联的 roleId。只是聚集索引查找。
| 归档时间: |
|
| 查看次数: |
1119 次 |
| 最近记录: |