天天看点

执行计划级别mysql 2ef_mysql执行计划分析

mysql> desc select * from oldboy.t_100w where k2=‘EF12‘\G

*************************** 1. row ***************************

id: 1

select_type: SIMPLE

table: t_100w

partitions: NULL

type: ref----------#索引级别

possible_keys: idx_k2

key: idx_k2

key_len: 17

ref: const

rows: 29

filtered: 100.00

Extra: NULL----------#额外信息

1 row in set, 1 warning (0.22 sec)

type: ref----------#索引级别:

ALL:全表扫描,不走索引

全表查询,不以索引列(k1)为查询条件的语句,不等于号,前后百分号,not in语句,等都不走索引

select * from t_100w;

select * from t_100w where k1=‘aaa‘;

select * from t_100w where k2 !=‘aaa‘;

select * from T_100w where k2 like ‘%aaa%‘;

index

全索引扫描,

mysql> desc select k2 from t_100w;

range

索引范围扫描

> < >= <= in or like

mysql> desc select * from world.city where id>3000;

mysql>select * from world.city where countrycode like ‘c%‘;

mysql> select * from world.city where countrycode in (‘CHN‘,‘USA‘);

实际生产中建议不要使用in,or或like,因为查询时不走指针,多条件查询时,建议使用union all进行拼接语句:

改写:

select * from world.city where countrycode=‘CHN‘

union all

select * from world.city where country=‘USA‘

备注:

实际生产中建议不要使用in,or或like,因为查询时不走指针,多条件查询时,建议使用union all进行拼接语句:

ref辅助索引等值查询级别效率要高于rang:

rang查询:

mysql> select * from world.city where countrycode in (‘CHN‘,‘USA‘);

改写ref级别:

select * from world.city where countrycode=‘CHN‘

union all

select * from world.city where country=‘USA‘

Extra: NULL ----------#额外信息

如果索引设计的不合理或者语句有问题就会出现using filesort这两个单词

例如我们想先查出某个国家然后再执行人口排序,取前10条。那么我们执行的语句是是:

desc select * from city where countrycode=‘CHN‘ order by population limit10;

此时你就会看到额外信息using fileout

显然上面的语句又有where又有order by,有点不合理,但实际中我们又需要这样过的语句,先查出国家,然后执行人口排序,取前十,怎么优化呢?

这是就需要用到了联合索引

mysql> alter table city add index idx_co_po(countrycode,population);

desc select * from city where countrycode=‘CHN‘ order by population limit10;

如果数据库查询操作突然变得很慢,可通过以下步骤尝试解决:

1查看哪条语句执行时间比较长

mysql> show full processlist;

2查看执行计划,看看那条执行语句最慢,并检查是否是语句的问题:

desc select * from world.city where countrycode !=‘CNH‘;

例如看看type索引优先级是啥?看看可能索引possible_keys是啥?实际索引key是啥?

假如说没走索引,看看语句中的where条件,group by的条件和order by的条件,join on的条件等,看看是什么原因导致的不走索引

查询而导致的数据库慢,如果是语句本身的问题,就要考虑改写语句了

原文:https://www.cnblogs.com/tyjs09/p/14297153.html