数据库查询分为两种,全表扫描,索引扫描。
explain 关键字 判断sql语句是否用到索引
explain select * from grains_resource where os_family="RedHat" and id = 4053;
+----+-------------+-----------------+-------+---------------+---------+---------+-------+------+-------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-----------------+-------+---------------+---------+---------+-------+------+-------+
| 1 | SIMPLE | grains_resource | const | PRIMARY | PRIMARY | 4 | const | 1 | |
+----+-------------+-----------------+-------+---------------+---------+---------+-------+------+-------+
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不支持索引