索引优化实战三

川长思鸟来 2022-08-28 13:49 250阅读 0赞

一 索引列上不能有范围查询

存储引擎不能使用索引中范围条件右边的列。

二 实战

  1. # 全值匹配我最爱
  2. mysql> explain select * from staffs where name = 'July' and age=15 and pos='dev';
  3. +----+-------------+--------+------------+------+-------------------------+-------------------------+---------+-------------------+------+----------+-------+
  4. | id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
  5. +----+-------------+--------+------------+------+-------------------------+-------------------------+---------+-------------------+------+----------+-------+
  6. | 1 | SIMPLE | staffs | NULL | ref | index_staffs_nameAgePos | index_staffs_nameAgePos | 140 | const,const,const | 1 | 100.00 | NULL |
  7. +----+-------------+--------+------------+------+-------------------------+-------------------------+---------+-------------------+------+----------+-------+
  8. 1 row in set, 1 warning (0.00 sec)
  9. # 存储引擎不能使用索引中范围条件右边的列:name用于索引,age用于排序,post不能用于索引。
  10. mysql> explain select * from staffs where name = 'July' and age>15 and pos='dev';
  11. +----+-------------+--------+------------+-------+-------------------------+-------------------------+---------+------+------+----------+-----------------------+
  12. | id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
  13. +----+-------------+--------+------------+-------+-------------------------+-------------------------+---------+------+------+----------+-----------------------+
  14. | 1 | SIMPLE | staffs | NULL | range | index_staffs_nameAgePos | index_staffs_nameAgePos | 78 | NULL | 1 | 33.33 | Using index condition |
  15. +----+-------------+--------+------------+-------+-------------------------+-------------------------+---------+------+------+----------+-----------------------+
  16. 1 row in set, 1 warning (0.00 sec)

三 建议

建索引时将可能做范围查询的字段的索引顺序放在最后。

发表评论

表情:
评论列表 (有 0 条评论,250人围观)

还没有评论,来说两句吧...

相关阅读

    相关 索引优化实战

     一  不要在索引列上做任何计算 不在索引列上做任何操作(计算、函数、(自动 or 手动)类型转换),会导致索引失效而转向全表扫描。 二 实战 等号左边