explain语法
1 |
mysql> explain select * from user where age='30' and money > '1000000' and look='beautiful'; |
1.查看中国和美国的城市人口数量
1 2 3 4 5 |
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.查看三个命令的执行计划
1 2 3 4 5 |
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.查询结果注释
1 2 3 4 5 6 7 8 9 10 11 12 13 |
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 #使用了索引 |
查询数据的方式
全表扫描
1 2 3 4 5 6 7 8 |
#1.什么是全表扫描? 读取整个表的数据,使用explain语句查询执行计划中,type列的值是ALL #2.什么时候使用全表扫描 1)查询表中所有数据的时候 mysql> explain select * from city; 2)没有走索引的时候 mysql> explain select name,population from city where population='92020'; |
索引扫描
#从上到下查询速度依次越来越快
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;