外键会提高查询性能吗?

Does Foreign Key improve query performance?(外键会提高查询性能吗?)
本文介绍了外键会提高查询性能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有 2 个表,Products 和 ProductCategories.两个表在 CategoryId 上都有关系.这就是查询.

Suppose I have 2 tables, Products and ProductCategories. Both tables have relationship on CategoryId. And this is the query.

SELECT p.ProductId, p.Name, c.CategoryId, c.Name AS Category
FROM Products p
INNER JOIN ProductCategories c ON p.CategoryId = c.CategoryId
WHERE c.CategoryId = 1;

当我创建执行计划时,表 ProductCategories 执行集群索引查找,这是预期的.但是对于表产品,它执行集群索引扫描,这让我怀疑.为什么 FK 无助于提高查询性能?

When I create execution plan, table ProductCategories performs cluster index seek, which is as expectation. But for table Products, it performs cluster index scan, which make me doubt. Why FK does not help improve query performance?

所以我必须在 Products.CategoryId 上创建索引.当我再次创建执行计划时,两个表都执行索引查找.并且估计子树成本降低了很多.

So I have to create index on Products.CategoryId. When I create execution plan again, both tables perform index seek. And estimated subtree cost is reduced a lot.

我的问题是:

  1. FK除了有助于关系约束,还有其他用处吗?它会提高查询性能吗?

  1. Beside FK helps on relationship constraint, does it have any other usefulness? Does it improve query performance?

我应该在所有表中的所有 FK 列(喜欢的 Products.CategoryId)上创建索引吗?

Should I create index on all FK columns (liked Products.CategoryId) in all tables?

推荐答案

外键是参照完整性工具,而不是性能工具.至少在 SQL Server 中,创建 FK 不会创建关联索引,您应该在所有 FK 字段上创建索引以缩短查找时间.

Foreign Keys are a referential integrity tool, not a performance tool. At least in SQL Server, the creation of an FK does not create an associated index, and you should create indexes on all FK fields to improve look up times.

这篇关于外键会提高查询性能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)