show global status like 'Com_______'
执行时间超过10秒的sql语句
show profiles帮助我们了解时间都耗费到哪里了
#查看每一条sql的耗时情况
show profiles
#查看指定query_id的sql语句各个阶段的耗时情况
show profile for query query_id
#查看指定query_id的sql语句cpu的耗时情况
show profile cpu for query query_id
explain select * from emp e, dept d where e.dept_id = d.id;
查询选修sql的学生,涉及学生表、课程表、中间表。
先从课程表通过mysql查询课程id
再从中间表通过课程id查询学生id
最后从学生表通过学生id获得行信息
表示连接类型,性能由好到差的连接类型为NULL、system、const、eq_ref、ref、range、index、all。
explain select 'A', 这种无聊没意义的语句的type是null
system访问系统表
const 主键、唯一索引查询:select *from emp where id = 1
ref 非唯一性索引查询:select *from emp where name = 'Xiaohong'
可能用到的索引
用到的索引
索引字段最大可能长度
mysql认为必须要执行查询的行数
返回结果的行数占需读取行数的百分比
针对sn字段创建索引
create index idx_sku_sn on tb_sku(sn);
接下来执行索引的话就很快啦!
select * from tb_sku where sn = '100000000153'
如果最左侧索引列不存在,则全部失效
如果跳跃某一列,后面的字段索引失效
注意 : 最左前缀法则中指的最左边的列,是指在查询时,联合索引的最左边的字段 ( 即是第一个字段 ) 必须存在,与我们编写 SQL 时,条件编写的先后顺序无关。
explain select * from tb_user where profession = '软件工程' and age = 31 and status
= '0';
explain select * from tb_user where profession = '软件工程' and age = 31 and status
= 0;
explain select * from tb_user where profession like '软件%'; -- 走
explain select * from tb_user where profession like '%工程'; -- 不走
explain select * from tb_user where profession like '%工%'; -- 不走
or分隔开的条件,如果or前面的条件中的列有索引,而后面的条件列中没有索引,那么涉及的索引都不会被用到
explain select * from tb_user where id = 10 or age = 23;
mysql评估使用索引比扫描全表更慢,则不使用索引
select * from tb_user where phone >= '17799990005'; --全表扫描
select * from tb_user where phone >= '17799990015'; --索引生效
explain select * from tb_user where profession is null;
explain select * from tb_user where profession is not null;
如果把表里的profession全都set为null,那么is null就查选表,is not null就走索引
加入人为提示达到优化操作
explain select * from tb_user use index(idx_user_pro) where profession = '软件工
程';
explain select * from tb_user ignore index(idx_user_pro) where profession = '软件工
程';
explain select * from tb_user force index(idx_user_pro) where profession = '软件工
程';
explain select id, profession from tb_user where profession = '软件工程' and age =
31 and status = '0' ;
explain select id, profession,age, status from tb_user where profession = '软件工程'
and age = 31 and status = '0' ;
explain select id, profession,age, status, name from tb_user where profession = '软
件工程' and age = 31 and status = '0' ;
explain select * from tb_user where profession = '软件工程' and age = 31 and status
= '0';
select id,name,gender from tb_user where name = 'Arm';
需要使用二级索引,name要到聚集索引中根据id查询,也就是需要回表查询,效率比较低
使用select * 很容易出现回表查询的情况
将字符串的一部分前缀建立索引
create index idx_email_5 on tb_user(email(5));
在创建联合索引的时候,需要考虑索引的顺序。