MySQL复合索引前导列特性

复合索引前导列特性

在有些文章中也称之为【索引的最佳左前缀特性】
叫什么不重要,重要的是要理解他,会去运用他----柳峰老师

【重点】

在这里插入图片描述

创建一个复合索引
create index idx_name_salary_dept on employee(name,salary,dept);

查询数据
mysql> explain select * from employee where name='墨菲'\G;
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: employee
   partitions: NULL
         type: ref
possible_keys: idx_name_salary_dept
          key: idx_name_salary_dept
      key_len: 123
          ref: const
         rows: 1
     filtered: 100.00
        Extra: NULL
1 row in set, 1 warning (0.13 sec)

ERROR:
No query specified
mysql> explain select * from employee where name='墨菲' and salary='8800'\G;
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: employee
   partitions: NULL
         type: ref
possible_keys: idx_name_salary_dept
          key: idx_name_salary_dept
      key_len: 128
          ref: const,const
         rows: 1
     filtered: 100.00
        Extra: NULL
1 row in set, 1 warning (0.30 sec)

ERROR:
No query specified

查看name和dept是否有用到索引
explain select * from employee where name='墨菲' and dept='部门A'\G;

mysql> explain select * from employee where name='墨菲' and dept='部门A'\G;
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: employee
   partitions: NULL
         type: ref
possible_keys: idx_name_salary_dept
          key: idx_name_salary_dept
      key_len: 123
          ref: const
         rows: 1
     filtered: 10.00
        Extra: Using index condition
1 row in set, 1 warning (0.05 sec)

ERROR:
No query specified
结果是一样的,也有用到索引

如果仅仅是部门A的情况,我们发现并没有用到索引
mysql> explain select * from employee where  dept='部门A'\G;
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: employee
   partitions: NULL
         type: ALL
possible_keys: NULL
          key: NULL
      key_len: NULL
          ref: NULL
         rows: 13
     filtered: 10.00
        Extra: Using where
1 row in set, 1 warning (0.00 sec)

ERROR:
No query specified
发布了82 篇原创文章 · 获赞 19 · 访问量 4635

猜你喜欢

转载自blog.csdn.net/ABCisCOOL/article/details/105351432