explain详解

1.explain语法

mysql> explain select * from user where age='30' and money > '1000000' and look='beautiful';
#1.查看中国和美国的城市人口数量
mysql> select name,population from city where countrycode='CHN' or countrycode='USA';

mysql> select name,population from city where countrycode in ('CHN','USA');

mysql> select name,population from city where countrycode='CHN' union all select name,population from city where countrycode='USA';

#2.查看三个命令的执行计划
mysql> explain select name,population from city where countrycode='CHN' or countrycode='USA';

mysql> explain select name,population from city where countrycode in ('CHN','USA');

mysql> explain select name,population from city where countrycode='CHN' union all select name,population from city where countrycode='USA';

#3.查询结果注释
id                    #执行顺序
table                #查询的表
type                #查询使用的类型
possible_keys         #可能使用的索引列
key                    #真正实用的索引列
key_len                #索引长度,前缀索引的长度
ref                    #查询级别是否达到ref级别
rows                #查询数据的数量
Extra
    Using temporary
    Using filesort             #使用了默认的文件排序(如果使用了索引,会避免这类排序)order by
    Using join buffer        #使用了 join on
    Using index condition    #使用了索引

2.group by扩展

#1.插入一个表
mysql> create table jixiao(id int,name varchar(10),money int,product varchar(10));

#2.插入数据
mysql> insert into jixiao values('1','邱二','100000','汽车'),('2','laocai','80000','汽车'),('3','dawei','700000','房地产'),('4','laozhao','800000','房地产');

#3.查询不同行业总绩效
mysql> select sum(money),product from jixiao group by product;
+------------+-----------+
| sum(money) | product   |
+------------+-----------+
|    1500000 | 房地产    |
|     180000 | 汽车      |
+------------+-----------+
2 rows in set (0.00 sec)

#4.查询不同行业绩效最高的那个人

3.查询数据的方式

1)全表扫描

#1.什么是全表扫描?
    读取整个表的数据,使用explain语句查询执行计划中,type列的值是ALL
    
#2.什么时候使用全表扫描
    1)查询表中所有数据的时候
    mysql> explain select * from city;
    2)没有走索引的时候
    mysql> explain select name,population from city where population='92020';

2)索引扫描

#从上到下查询速度依次越来越快
1.index            #全索引扫描
    mysql> explain select name from city;

2.range            #范围查询使用该级别,但是当查询数据量过大的时候不走索引
    mysql> explain select name,population from city where countrycode='CHN' or countrycode='USA';
    mysql> explain select name,population from city where population > 3000000;
    
3.ref            #使用精确查询
    mysql> explain select name,population from city where countrycode='CHN';

4.eq_ref        #使用join on时可能出现该级别
    mysql> explain select city.name,city.population,country.name from country join city on city.countrycode=country.code where city.population < 100;

5.const            #当查询条件是主键或者唯一键的时候
    mysql> explain select * from city where id='1';

6.system        #跟const平级,当查询的数据所在表数据量很小的时候,并且查询条件使用主键或者唯一键

7.null            #当不用读取数据库数据的时候
    mysql> explain select max(population) from city;
原文地址:https://www.cnblogs.com/chenlifan/p/13907299.html