InnoDB 中二级索引扫描如何工作?

发布于 2024-10-13 04:15:42 字数 149 浏览 2 评论 0原文

InnoDB 有两种类型的索引:主索引(聚集索引)和辅助索引(带有主索引键)。

当我输入扫描由二级索引索引的字段的查询时,我的问题开始了。 InnoDB是否扫描二级索引并逐条检索满足条件的记录? 如果我在二级索引中有50次命中,那么InnoDB会寻找50次主索引吗?

InnoDB has two types of indexes: primary (clustered), and secondary (with pimary index key).

When I type query that scan fields indexed by secondary index my question starts.
Is InnoDB scan secondary index and retrive one by one records that hit condition?
If I have 50 hits in secondary index InnoDB seek 50 times primary index?

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

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

发布评论

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

评论(1

千纸鹤 2024-10-20 04:15:42

InnoDB是否扫描二级索引并逐条检索满足条件的记录?

如果您选择二级索引未覆盖的列,那么是的,它应该从表(聚集索引)中检索它们。

如果您有这种布局:

CREATE TABLE a (id INT NOT NULL PRIMARY KEY, ca INT NOT NULL, cb INT NOT NULL, KEY(ca))

SELECT  cb
FROM    a
WHERE   ca = $some_value

会发生以下情况:

  1. 使用 B-Tree 查找InnoDB 找到 ca 索引中的第一条记录> 包含 $some_value

  2. 然后遍历索引,逐条获取记录,直到找到第一个大于 $some_value 的记录。 p>

  3. 由于索引中只包含ca(键列)和id(行指针),InnoDB需要查找<的值code>cb 在表本身中。

  4. 对于索引中的每条记录,它都会获取id 的值并在表中搜索它。由于该表实际上是 id 上的聚集索引,因此使用 B-Tree 搜索。

但是,如果您有以下查询:

SELECT  ca, id
FROM    a
WHERE   ca = $some_value

,则可以直接从索引检索所有内容,并且不会执行步骤 34。它在查询计划中显示为使用索引

如果我在二级索引中有 50 次命中,InnoDB 会寻找 50 次主索引吗?

是的(关于上面的评论)

Is InnoDB scan secondary index and retrive one by one records that hit condition?

If you select columns not covered by the secondary index, then yes, it should retrieve them from the table (the clustered index).

If you have this layout:

CREATE TABLE a (id INT NOT NULL PRIMARY KEY, ca INT NOT NULL, cb INT NOT NULL, KEY(ca))

SELECT  cb
FROM    a
WHERE   ca = $some_value

the following happens:

  1. Using a B-Tree seek, InnoDB finds the first record in the index on ca which holds $some_value

  2. It then traverses the index, taking records one by one, until it finds the first record greater than $some_value.

  3. Since only ca (key column) and id (row pointer) are contained in the index, InnoDB needs to find values of cb in the table itself.

  4. For each record in the index, it takes the value of id and searches the table for it. Since the table is in fact a clustered index on id, B-Tree search is used for that.

However, if you have this query:

SELECT  ca, id
FROM    a
WHERE   ca = $some_value

, then everything can be retrieved right from the index, and steps 3 and 4 are not performed. It is shown in the query plan as using index.

If I have 50 hits in secondary index InnoDB seek 50 times primary index?

Yes (with regard to the comment above)

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