Mysql Documentation 阅读笔记: 索引原理
MYSQL优化: How MySQL Uses Indexes
Indexes are used to find rows with specific column values quickly. Without an index, MySQL must begin with the first row and then read through the entire table to find the relevant rows. The larger the table, the more this costs. If the table has an index for the columns in question, MySQL can quickly determine the position to seek to in the middle of the data file without having to look at all the data. This is much faster than reading every row sequentially.
索引是为了更快的搜索指定的列;没有索引的搜索会搜索整张表;
Most MySQL indexes (PRIMARY KEY, UNIQUE, INDEX, and FULLTEXT) are stored in B-trees.
大部分索引都以B树的方式存储,B树的优点:搜索树、Log n 的时间复杂度。具体B树在Mysql存储中的应用待深入研究。
MySQL uses indexes for these operations:
- To find the rows matching a WHERE clause quickly: 更快的匹配到满足where条件的行。
- To eliminate rows from consideration. If there is a choice between multiple indexes, MySQL normally uses the index that finds the smallest number of rows (the most selective index):如果是多索引的话,通常Mysql会选择最少行的那个索引;
- 如果一张表里创建了多列索引(col1,col2,col3),那么基于左侧分割的(col1),(col1,col2),(col1,col2,col3)的索引都是可用的.
If the table has a multiple-column index, any leftmost prefix of the index can be used by the optimizer to look up rows. For example, if you have a three-column index on (col1, col2, col3), you have indexed search capabilities on (col1), (col1, col2), and (col1, col2, col3).
- 在操作操作JOIN的返回连接表的行时,对于相同类型和长度的列,索引会表现的更高效。
To retrieve rows from other tables when performing joins. MySQL can use indexes on columns more efficiently if they are declared as the same type and size.
- 在对有索引的列使用MIN() 、MAX()时的优化:预处理器会先处理匹配WHERE,然后在结果里面,分别的去执行每一个MIN() 、 MAX() 表达式,将他们替换成常量,知道所有的表达式都执行完,然后一次返会结果。
# age 列如果已添加索引,会依照上述流程执行
SELECT MIN(age), MAX(age) FROM students WHERE gender = 'male';
- 在GROUP 和 ORDER 操作时,如果是多列索引,仍然按照leftmost原则使用索引。
- 查询的时候使用指定需要的(索引)列,会比查询所有列要更高效。
- 索引在数据量小的表上的优势体现并不明显。