问题描述
我对 MySQL 索引的工作原理很感兴趣,更具体地说,它们如何在不扫描整个表的情况下返回请求的数据?
I am really interested in how MySQL indexes work, more specifically, how can they return the data requested without scanning the entire table?
这是题外话,我知道,但如果有人可以向我详细解释这一点,我将非常非常感激.
It's off-topic, I know, but if there is someone who could explain this to me in detail, I would be very, very thankful.
推荐答案
基本上,表上的索引就像一本书中的索引(这就是名称的来源):
Basically an index on a table works like an index in a book (that's where the name came from):
假设您有一本关于数据库的书,并且您想找到一些关于存储的信息.如果没有索引(假设没有其他帮助,例如目录),您必须一页一页地浏览,直到找到主题(即全表扫描
).另一方面,索引有一个关键字列表,因此您可以查阅索引并看到在第 113-120,231 和 354 页上提到了 storage
.然后您可以直接翻到这些页面,不进行搜索(即使用索引进行搜索,速度稍快一些).
Let's say you have a book about databases and you want to find some information about, say, storage. Without an index (assuming no other aid, such as a table of contents) you'd have to go through the pages one by one, until you found the topic (that's a full table scan
).
On the other hand, an index has a list of keywords, so you'd consult the index and see that storage
is mentioned on pages 113-120,231 and 354. Then you could flip to those pages directly, without searching (that's a search with an index, somewhat faster).
当然,索引的有用程度取决于很多事情 - 几个例子,使用上面的明喻:
Of course, how useful the index will be, depends on many things - a few examples, using the simile above:
- 如果你有一本关于数据库的书并且索引了数据库"这个词,你会看到它在第 1-59、61-290 和 292 到 400 页中被提及.在这种情况下,索引没有多大帮助一页一页地浏览页面可能会更快(在数据库中,这是选择性差").
- 对于一本 10 页的书,制作索引是没有意义的,因为您最终可能会得到一本以 5 页索引为前缀的 10 页书,这很愚蠢 - 只需扫描 10 页即可完成了.
- 索引也需要有用 - 通常没有必要建立索引,例如每页字母L"出现的频率.
这篇关于MySQL 索引如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!