mysql explain 查看查询索引

数据库查询分为两种,全表扫描,索引扫描。sql

explain 关键字 判断sql语句是否用到索引数据库


explain select * from grains_resource where os_family="RedHat" and id = 4053;
优化

+----+-------------+-----------------+-------+---------------+---------+---------+-------+------+-------+spa

| id | select_type | table           | type  | possible_keys | key     | key_len | ref   | rows | Extra |索引

+----+-------------+-----------------+-------+---------------+---------+---------+-------+------+-------+table

|  1 | SIMPLE      | grains_resource | const | PRIMARY       | PRIMARY | 4       | const |    1 |       |select

+----+-------------+-----------------+-------+---------------+---------+---------+-------+------+-------+sql语句

  • type 为const,意味着经过索引直接找到匹配行,因此优化器认为它的时间复杂度为常量。
    数据

  • key为PRIMARY,意味着此次查询使用了主键索引。查询




explain select * from grains_resource where os_family="RedHat";

+----+-------------+-----------------+------+---------------+------+---------+------+-------+-------------+

| id | select_type | table           | type | possible_keys | key  | key_len | ref  | rows  | Extra       |

+----+-------------+-----------------+------+---------------+------+---------+------+-------+-------------+

|  1 | SIMPLE      | grains_resource | ALL  | NULL          | NULL | NULL    | NULL | 51752 | Using where |

+----+-------------+-----------------+------+---------------+------+---------+------+-------+-------------+

type是all,表明此次查询是全表扫描,key为null 没用索引。


os_family字段加入索引

explain select * from grains_resource where os_family="RedHat";

+----+-------------+-----------------+------+---------------+-----------+---------+-------+-------+-------------+

| id | select_type | table           | type | possible_keys | key       | key_len | ref   | rows  | Extra       |

+----+-------------+-----------------+------+---------------+-----------+---------+-------+-------+-------------+

|  1 | SIMPLE      | grains_resource | ref  | os_family     | os_family | 138     | const | 26315 | Using where |

+----+-------------+-----------------+------+---------------+-----------+---------+-------+-------+-------------+

使用了os_family这个索引


explain select * from grains_resource where os_family like "%RedHat";

+----+-------------+-----------------+------+---------------+------+---------+------+-------+-------------+

| id | select_type | table           | type | possible_keys | key  | key_len | ref  | rows  | Extra       |

+----+-------------+-----------------+------+---------------+------+---------+------+-------+-------------+

|  1 | SIMPLE      | grains_resource | ALL  | NULL          | NULL | NULL    | NULL | 52631 | Using where |

+----+-------------+-----------------+------+---------------+------+---------+------+-------+-------------+

like不支持索引

相关文章
相关标签/搜索