Mysql索引总结

一、索引分类

  1. Hash索引:Hash 索引查询效率很高,时间复杂度O(1)。Mysql Innodb引擎不支持hash索引的。Hash索引适合精确查找,不适合范围查找。
  2. 平衡二叉树:时间复杂度为 O(n),根节点会变,数据量多,层次多,磁盘IO多。
  3. B树:每个节点中不仅包含数据的 key 值,还有 data 值。数据量较大的时候,同样会导致B树很深,从而增加了磁盘 IO 的次数。
  4. B+树:所有的数据节点都在最后一层上,叶子节点按关键字排序,从左到右指针连接,层级更少,查询稳定。

二、主键索引

搜索过程:索引页——> 索引页——> 数据页

  • 索引页 + 数据页组成的B+树就是聚簇索引。
  • InnoDB聚簇索引:

  • 聚集索引叶节点存储整行数据(即数据页)

    [En]

    the clustered index leaf node stores the whole row of data (that is, data pages)*

  • 普通索引叶子节点:

三、回表与索引覆盖

  • 只有索引字段的值保存在非聚集索引(普通索引)中。联邦索引先按第一列排序,然后按第二列排序。仍然排序,然后按主键索引排序)和主键索引值。
    [En]

    only the values of the index fields are saved in the non-clustered index (normal index). The federated index is sorted by the first column and then by the second column. Sort, all the same, and then sort by primary key index) and the value of the primary key index.*

  • 回表:Select的where条件中是非聚簇索引,查询需要返回非聚簇索引中不包含的字段,此时需要用主键索引再查一次聚簇索引;
  • 索引覆盖率:创建要查询到联合索引中的字段。这种查询不需要返回表。
    [En]

    Index coverage: create the fields to be queried into the federated index. This kind of query does not need to return to the table.*

四、联合索引

  • 联合索引中多列条件为OR关联时,索引不生效;
  • 最左列必须在查询条件下,否则不生效–最左匹配原则
    [En]

    the leftmost column must be in the query condition, otherwise it will not take effect-leftmost matching principle*

  • 在联合索引范围查询中,第一列是范围查询,后续的列范围查询不能索引。只有当第一列是等价查询时,后续列才可以使用范围查询。
    [En]

    in a joint index range query, the first column is a range query, and the subsequent column range query cannot be indexed. Only when the first column is an equivalent query, the subsequent column can use the range query.*

  • groupBy+索引,效率特别高,不需要建中间表,也不需要排序;

五、索引优化技巧

  • 大字段建索引时,可以只取字段的前半部分,例: CREATE INDEX table ON dual(address(20));
  • 当值高于列中的列时,查询优化器将放弃索引并扫描整个表。默认情况下,比例分隔线为30%。
    [En]

    when a value is higher than the column in a column, the query optimizer will abandon the index and scan the full table. The scale dividing line is 30% by default.*

  • orderBy和groupBy后的字段最好建索引,不会产生中间表;
  • 隐式类型(”1″=> 1)转换会导致索引失效;
  • 深分页查询时使用Limit时,先嵌套子查询,把id查出来,再通过id用where条件搜索,可以避免回表;

Original: https://www.cnblogs.com/zhusihua/p/14980341.html
Author: 拉通对齐端到端
Title: Mysql索引总结

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/507912/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球