SQL Server 2008 中是否有外键索引
SQL Server 2008 中是否需要向外键添加索引,或者这是默认处理的。在我的许多表中,我都有一个指向用户帐户表的 FK,并且大多数选择都是通过此 WHERE Account_FK = id
进行的。所以我希望索引可以在这里快速获得性能胜利。
Is there any need to add an index to a foreign key in SQL Server 2008 or is this handled by default. In many of my tables I have one FK that points to the user account table and most selects are made with this WHERE Account_FK = id
. So index could be a quick performance win here i hope.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通常,您希望所有
JOIN
键都具有索引,因此可以添加索引。如果它是复合键,请确保将所有相关字段以适当的顺序放入索引键列表中。
据我所知,在 SQL Server 中自动创建索引的唯一一次是当您将主键添加到堆(非索引表)时 - PK 会自动分配为聚集索引键;或者,正如 Damien 下面指出的,当您向一个字段或一组字段添加
UNIQUE
约束时。As a rule, you want all your
JOIN
keys to have indexes on them, so yes add an index.If it's a composite key make sure to put all the relevant fields in the index key list in an appropriate order.
To my knowledge the only times an index is created automatically in SQL Server is when you add a primary key to a heap (non-indexed table) - the PK is assigned as the Clustered Index Key automatically; or, as Damien points out below, when you add a
UNIQUE
constraint to a field or set of fields.向 FK 添加索引的一个不太明显的原因是当您想要删除主表(您的用户帐户表)中的一行时。 SQL Server 对每个 FK 关系进行检查,以查看是否有任何行会阻止删除,并且使用子表中 FK 列上的索引,检查速度要快得多。
One not so obvious reason to add an index to the FK is for when you want to delete a row in the master table (your user account table). SQL Server does a check for every FK relation to see if there are any rows that would prevent the deletion, and that check is a lot quicker with an index on the FK column in the child table(s).