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原則使用索引。
  • 查詢的時候使用指定需要的(索引)列,會比查詢所有列要更高效。
  • 索引在數據量小的表上的優勢體現并不明顯。
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容