以下是来自 MySQL Documentation 的文字:
- To find the
MIN()
orMAX()
value for a specific indexed column key_col. This is optimized by a preprocessor that checks whether you are using WHERE key_part_N = constant on all key parts that occur before key_col in the index. In this case, MySQL does a single key lookup for eachMIN()
orMAX()
expression and replaces it with a constant. If all expressions are replaced with constants, the query returns at once. For example:
SELECT MIN(key_part2),MAX(key_part2)
FROM tbl_name WHERE key_part1=10;
To sort or group a table if the sorting or grouping is done on a leftmost prefix of a usable index (for example, ORDER BY key_part1, key_part2). If all key parts are followed by
DESC
, the key is read in reverse order.In some cases, a query can be optimized to retrieve values without consulting the data rows. (An index that provides all the necessary results for a query is called a covering index.) If a query uses from a table only columns that are included in some index, the selected values can be retrieved from the index tree for greater speed:
SELECT key_part3 FROM tbl_name
WHERE key_part1=1
我根本无法理解这些要点以及 MySQL Documentation 中的相应代码.
有人请让事情变得简单,以便澄清事情让我理解。
我不是在问什么是索引以及如何工作等等。
我只想了解这些句子试图表达的意思以及代码中发生了什么?
key_par_N 是什么,在这里使用它们的目的是什么?
在此上下文中,术语关键部分的实际含义是什么?
索引中 key_col 之前出现的所有关键部分是什么意思?
我们应该对 MIN()
和 MAX()
进行罚款的列 key_col 在哪里值(查看第一行: 查找特定索引列的 MIN()
或 MAX()
值 key_col.)?
有人请让我清楚一切。
注意:我已经看到了 this问题是问同样的事情,但它收到了一个普遍的答案,这个答案并不特定于手册中给出的解释和代码。所以,我问这个问题是为了得到准确和具体的答案。所以,请不要将我的问题标记为重复。
最佳答案
在 SQL 中,您可以创建索引以索引多个列,例如,create index idx on t1 (key_colX, key_colY)
。现在 key_part1 是 key_colX
而 key_part2 是 key_colY
。顺序很重要!
假设我们使用一个 bTree 作为索引结构,然后首先根据 key_part1 组织元素,如果两个元素的 key_part1 相等则根据 key_part2。现在,如果您发出查询并将 key_part1 = 10 设置为(常数)值,数据库可以快速找到 bTree 的子树,其中 key_part1 = 10。此子树中的所有元素都根据 key_part2 进行组织,这使得 Min() 或Max() 非常有效。
如果你用另一种方式尝试查询
SELECT MIN(key_part1),MAX(key_part1) FROM tbl_name WHERE key_part2=10;
那么索引就不能使用了。
所以上面基本上说如果您的查询可以利用索引列的顺序,您可以更有效地回答查询。
关于mysql - 索引如何工作以查找特定索引列的 MIN() 或 MAX() 值并在以下情况下对表进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47690334/