立即学习:https://edu.youkuaiyun.com/course/play/25283/297145?utm_source=blogtoedu
explain +sql ;
id 值相同,从上往下顺序执行
表的执行顺序 因数量的个数改变而改变的原因:笛卡尔积
数据小的表,优先查询
id值不同:id值越大越优先查询
(2)select_type
primary :包含子查询SQL中的主查询(最外层)
SUBQUERY:包含子查询SQL中的子查询(非最外层)
simple:简单查询(不包含子查询、union)
derived:衍生查询(使用到了临时表)
a.在from 子查询中只有一张表
b.在from子查询中,如果有table1 union table2,则table1 就是derived table2 就是union
union result 表(不常见):告知开发人员,那些表之间存在union查询
system >const > eq_ref >ref> fulltext >ref_or_null >index_merge > unique_subquery >index_
(3)type:索引类型、类型
system >const > eq_ref >ref>range>index>all 要对type进行优化的前提:有索引
其中:system ,const 只是理想情况;实际能达到ref>range
system(忽略):只有一条数据的系统:或衍生表只有一条数据的主查询
增加索引:
alter table test01 add constraint tid_pk primary key(tid);
const:仅仅能查到一条数据的SQL,用于Primary key 或unique索引(类型与索引类型有关)
eq_ref :唯一性索引;对于每个索引建的查询,返回匹配唯一行数据(有且只有一个,不能多、不能0)
常见于唯一索引和主键索引。
alter table teacherCard add constraint pk_tcid primary key(tcid);
alter table teacher add constraint uk_tcid unique index(tcid);
range :检索指定范围的行,where 后面是一个范围查询(between ,> <>=, 特殊:in有时候会失效,从而转为无索引all )
index:查询全部索引中数据
只需要扫描索引表,不需要所有表中的所有数据
all:查询全部数据
需要全表所有,即需要所有表中的所有数据
system/const:结果只有一条数据
eq_ref:结果多条,但是每条数据是唯一的;
ref:结果多条;但是每条数据是0条或多条;
(4)possible_keys:可能用到的索引,是一种预测,不准。
如果possible_key /key 是NULL,则说明没用索引
(5)key:实际使用到的索引
(6)key_len:索引的长度 作用:用于判断复合索引受被完全使用。
create table test_k1(
name char(20) not null default ''
);
alter table test_kl add index index_name(name);
utf8:1个字符3个字节
gbk:1个字符2个字节
latin:1个字符1个字节