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不支持索引

相關文章
相關標籤/搜索