MySQL之explain的type列

WBOY
풀어 주다: 2016-06-07 15:10:11
원래의
997명이 탐색했습니다.

欢迎进入Linux社区论坛,与200万技术人员互动交流 >>进入 建表及插入数据: create table a(id int primary key); create table a_info(id int, title char(1), key(id)); insert into a value(1),(2); insert into a_info value(1, 'a')

欢迎进入Linux社区论坛,与200万技术人员互动交流 >>进入

 

  建表及插入数据: create table a(id int primary key); create table a_info(id int, title char(1), key(id)); insert into a value(1),(2); insert into a_info value(1, 'a'),(2, 'b'); 现在 a_info 表 id 列变为普通索引(非唯一性索引): mysql> explain select * from a join a_info using(id) where a.id=1;

  …+--------+-------+…

  …| table | type |…

  …+--------+-------+…

  …| a | const |…

  …| a_info | ref |…

  …+--------+-------+… a_info 表 type 变为 ref 类型了。所以,唯一性索引才会出现 eq_ref (非唯一性索引会出现 ref ),因为唯一,所以最多只返回一条记录,找到后无需继续查找,因此比 ref 更快。

  const 被称为"常量",这个词不好理解,不过出现 const 的话就表示发生下面两种情况:在整个查询过程中这个表最多只会有一条匹配的行,比如主键 id=1 就肯定只有一行,只需读取一次表数据便能取得所需的结果,且表数据在分解执行计划时读取。返回值直接放在 select 语句中,类似 select 1 AS f .可以通过 extended 选择查看内部过程:

  建表及插入数据: create table a(id int primary key, c1 char(20) not null, c2 text not null, c3 text not null); insert into a values(1, 'asdfasdf', 'asdfasdf', 'asdfasdf'), (2, 'asdfasdf', 'asdfasdf', 'asdfasdf'); mysql> explain extended select * from a where id=1\G

  …

  type: const

  possible_keys: PRIMARY

  key: PRIMARY

  … 用 show warnings 查看 MySQL 是如何优化的: mysql> show warnings\G

  …

  Message: select '1' AS `id`,'asdfasdf' AS `c1`,'asdfasdf' AS `c2`,'asdfasdf' AS

  `c3` from `test`.`a` where 1 查询返回的结果为: mysql> select * from a where id=1;

  +----+----------+----------+----------+

  | id | c1 | c2 | c3 |

  +----+----------+----------+----------+

  | 1 | asdfasdf | asdfasdf | asdfasdf |

  +----+----------+----------+----------+ 可以看出,返回结果中的字段值都以"值 AS 字段名"的形式直接出现在优化后的 select 语句中。修改一下查询: mysql> explain select * from a where id in(1,2)\G

  …

  type: range … 当返回结果超过 1 条时, type 便不再为 const 了。重新建表及插入数据: create table a (id int not null); insert into a value(1),(2),(3); mysql> explain select * from a where id=1\G

  …

  type: ALL 目前表中只有一条 id=1 的记录,但 type 已为 ALL ,因为只有唯一性索引才能保证表中最多只有一条记录,只有这样 type 才有可能为 const .为 id 加普通索引后, type 变为 ref ,改为加唯一或主键索引后, type 便变为 const 了。

  [1] [2] 

MySQL之explain的type列

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!