Mysql执行计划分析-type(access_type)

Mysql执行计划分析-type(access_type)

  access_type 即下图执行计划的 type 字段

  Mysql执行计划分析-type(access_type)

一、type(access_type) 以下类型

    Mysql执行计划分析-type(access_type)

二、类型示例

1、NULL

  NULL 不访问任何一个表

EXPLAIN select 1 from dual;

  输出

Mysql执行计划分析-type(access_type)

   Extra, 没有用到表。

2、system 和 const

  system 根据主键查询系统表且这个表只有一条记录【特殊的const场景】

  const 常量查询非常快。主键或者唯一索引的常量查询,表格最多只有1行记录符合查询。

EXPLAIN select * from myshop.ecs_users where user_id =1;

  输出

Mysql执行计划分析-type(access_type)

   type 为 const 常量查询

3、eq_ref

  eq_ref 使用PRIMARYKEY或者UNIQUE 和前面的结果集匹配。

  EXPLAIN select * from myshop.ecs_order_info b, myshop.ecs_users a where b.user_id = a.user_id;

  输出

Mysql执行计划分析-type(access_type)

  两次 id 为 1, 从上到下。

  第一次,查询 b 表, type 为 ALL 即全表扫描

  第二次查询 a 表,基于前面表的主键查询

4、ref

  ref 非聚集索引的常量查询。

EXPLAIN select * from myshop.ecs_users where email = 'onlyoneemail.com';

   输出

Mysql执行计划分析-type(access_type)

   ref 是 const 来自常量匹配,来自传入的参数

5、fulltext

  fulltext 查询的过程中,使用到了 fulltext 索引(fulltext index在innodb引擎中,只有5.6版本之后的支持)

EXPLAIN SELECT * FROM `demo-fulltext` WHERE MATCH(`remark`) AGAINST('Tony');

   输出

Mysql执行计划分析-type(access_type)

6、ref_or_null 

  ref_or_null 跟ref查询类似,在ref的查询基础上,加多一个null值的条件查询

EXPLAIN select * from myshop.ecs_users where email = 'onlyoneemail.com' OR email is null;

   输出

Mysql执行计划分析-type(access_type)

7、index_merge 

  index_merge 索引合并(分别两个查询条件的结果,再合并)

EXPLAIN select * from myshop.ecs_users where email = 'onlyoneemail.com' OR user_id = 1;

   输出

Mysql执行计划分析-type(access_type)

8、unique_subquery

  unique_subquery IN子查询的结果由聚族索引或唯一索引覆盖。

SET optimizer_switch='materialization=off';
EXPLAIN select * from myshop.ecs_users where user_id not in (
select user_id from myshop.ecs_users where email like '%.com%' );
SET optimizer_switch='materialization=on';

   输出

Mysql执行计划分析-type(access_type)

9、index_subquery 

  index_subquery 与unique_subquery类似,但是用的是二级索引

SET optimizer_switch='materialization=off';
EXPLAIN select * from myshop.ecs_users where email not in (
select email from myshop.ecs_users where email like '%.com%' );
SET optimizer_switch='materialization=on';

   输出

Mysql执行计划分析-type(access_type)


10、range

  =、<>、>、>=、<、<=、IS NULL、BETWEEN、IN、<=> (这是个表达式:左边可以推出右边,右边也可推出左边)

EXPLAIN select order_id from myshop.ecs_order_info where order_id < 10;

  输出

Mysql执行计划分析-type(access_type)

   type 为 range

11、full index scan

  index 执行full index scan直接从索引中取的想要的结果数据,也就是可以避免回表

EXPLAIN select order_id from myshop.ecs_order_info;

  输出

Mysql执行计划分析-type(access_type)

12、full table scan

   ALL 执行full table scan,这事最差的一种方式

EXPLAIN select pay_fee from myshop.ecs_order_info;

   输出

Mysql执行计划分析-type(access_type)

   没有索引,就是全表扫描, type 就是 ALL