在主键上创建多个索引是否有性能优势?外键?

发布于 2024-12-06 19:14:38 字数 258 浏览 3 评论 0原文

如果我有一个包含主键和外键的表,并且经常使用包含 (...WHEREprimary=n ANDforeign=x) 的查询来完成搜索,那么是否有任何性能使用两个键在 MySQL 中创建多重索引有什么好处?

我知道它们都已经是索引了,但是我不确定外键包含在另一个表中时是否仍然被视为索引。例如,MySQL 会查找主键,然后比较外键的所有值,直到找到正确的值,或者它是否已经知道它在哪里,因为外键也是一个索引?

更新:我正在使用 InnoDB 表。

If I have a table that has a primary key and a foreign key, and searches are frequently done with queries that include both (...WHERE primary=n AND foreign=x), is there any performance benefit to making a multiple index in MySQL using the two keys?

I understand that they are both indexes already, but I am uncertain if the foreign key is still seen as an index when included in another table. For example, would MySQL go to the primary key, and then compare all values of the foreign key until the right one is found, or does it already know where it is because the foreign key is also an index?

Update: I am using InnoDB tables.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

哽咽笑 2024-12-13 19:14:38

对于相等比较,您无法获得对主键索引的改进(因为此时最多只有一行可以匹配)。

访问路径是:

  1. 查看 Primary = n 的主键索引
  2. 从表中获取单个匹配行
  3. 使用表中的行检查任何其他条件

如果在主数据库上进行范围扫描,复合索引可能会有意义键并希望通过另一列缩小范围。

For equality comparisons, you cannot get an improvement over the primary key index (because at that point, there is at most just one row that can match).

The access path would be:

  1. look at the primary key index for primary = n
  2. get the single matching row from the table
  3. check any other conditions using the row in the table

A composite index might make some sense if you have a range scan on the primary key and want to narrow that down by the other column.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文