主键索引:B+树的叶子节点存储,非叶子节点存储主键。
辅助索引:B+树的叶子节点存储索引值和主键,非叶子节点存储索引值。
![](https://img.haomeiwen.com/i11772136/039fc124e651e7d2.png)
![](https://img.haomeiwen.com/i11772136/d26fa6c2dcfc3106.png)
尽可能使用联合索引,index(a,b,,c)覆盖index(a), index(a,b)
alter table t add index idx_a_b_c(a, b, c)
Select * from t where a = ? and b > ?
Select * from t where a > ? and b = ?
Select * from t where a = ? order by b
Select * from t where a = ? and b > ? and b < ? order by c
使用区分度高的列作为索引
not null 的列
数据类型简答的列,比如int比string好
索引的列不能参与计算
like %abc, not in (...), != 不能使用索引
如果查询中有某个列的索引范围,则其右边所有的列都无法使用索引优化。
select * from t where a = 1 or a = 2 // no
select * from t where id = 1 or id = 2 // yes
select * from t where a = 1 or id = 1 ; // no
select * from t where a = 1 and id = 1 // yes
select * from t where id + 1 = 2 // no
select * from t where id = 2 -1 // yes
limiy m,n 当m很大时,还会过滤很多数据。
最左前缀匹配
索引可以简单如一个列(a),也可以复杂如多个列(a, b, c, d),即联合索引。
如果是联合索引,那么key也由多个列组成,同时,索引只能用于查找key是否存在(相等),遇到范围查询(>、<、between、like左匹配)等就不能进一步匹配了,后续退化为线性查找。因此,列的排列顺序决定了可命中索引的列数。
如有索引(a, b, c, d),查询条件a = 1 and b = 2 and c > 3 and d = 4,则会在每个节点依次命中a、b、c,无法命中d。也就是最左前缀匹配原则。
类型的的是a = 1 and b = 2 and c = 3 order by d 的extra: using index condition,而a = 1 and b = 2 and c > 3 order by d 的extra: using filesort
select * from t where a > 100 order by a; // using index condition
select * from t where a > 100 order by b // using filesort
网友评论