![](/img/trans.png)
[英]Does clustered index on foreign key column increase join performance vs non-clustered?
[英]Is a non-clustered index implicitly created for each foreign key in a table?
如果我有这样的表:
CREATE TABLE MyTable
(
Id INT PRIMARY KEY IDENTITY(1, 1),
FooId INT NOT NULL FOREIGN KEY REFERENCES Foo(Id),
Data NVARCHAR(10) NOT NULL
);
可以进行以下观察:
将在表MyTable
上的主键列Id
上创建聚簇索引。
此外,可以推断,将在表Foo
上为其名为Id
主键创建聚簇索引。
题:
是否还会在MyTable表上创建外键Foo.Id
的索引?
换句话说,是为从属表上的每个外键隐式创建的非聚集索引。
换句话说,此模式中创建的索引总数将为2,如下所示:
MyTable
上主键Id
聚簇索引。 Foo
上主键Id
上的聚簇索引。 或者会有以下3个指数:
MyTable
上主键Id
聚簇索引。 Foo
上主键Id
上的聚簇索引。 MyTable
上的外键Foo(Id)
上的非聚集索引。 我的问题与Microsoft SQL Server 2014有关。
不,它不是自动创建的。 手动创建它是一个好习惯:
与主键约束不同, 当为表定义外键约束时,SQL Server默认不创建索引 。
但是,开发人员和数据库管理员手动添加它们并不罕见
CREATE TABLE MyTable(
Id int PRIMARY KEY IDENTITY(1, 1),
FooId int NOT NULL FOREIGN KEY REFERENCES Foo(Id),
Data nvarchar(10) NOT NULL,
);
exec sp_helpIndex 'MyTable'
index_name index_description index_keys
PK__MyTable__3214EC0742A69968 clustered, unique, primary key located on PRIMARY Id
显式索引创建:
CREATE TABLE MyTable (
Id int PRIMARY KEY IDENTITY(1, 1),
FooId int NOT NULL FOREIGN KEY REFERENCES Foo(Id),
Data nvarchar(10) NOT NULL,
INDEX FK_FooId nonclustered(FooId) -- inline syntax
);
exec sp_helpIndex 'MyTable'
index_name index_description index_keys
FK_FooId nonclustered located on PRIMARY FooId
PK__MyTable__3214EC0779B032FB clustered, unique, primary key located on PRIMARY Id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.