diff --git "a/_posts/2019-05-09-MySQL_\344\270\255\347\232\204\347\264\242\345\274\225.md" "b/_posts/2019-05-09-MySQL_\344\270\255\347\232\204\347\264\242\345\274\225.md" index f89205ed..a8a55c6e 100644 --- "a/_posts/2019-05-09-MySQL_\344\270\255\347\232\204\347\264\242\345\274\225.md" +++ "b/_posts/2019-05-09-MySQL_\344\270\255\347\232\204\347\264\242\345\274\225.md" @@ -192,6 +192,53 @@ INDEX (col1, col2) 不同存储引擎对其支持情况不一,详见 [Spatial Indexes](https://dev.mysql.com/doc/refman/8.0/en/create-index.html#create-index-spatial)。 +## 索引的查看 + +通过如下语句查看有哪些索引: + +```sql +SHOW INDEX FROM table_name; +``` + +e.g.: + +以 [employees 示例数据库](https://github.com/wayou/wayou.github.io/issues/82)中 titles 表为例,先创建索引 + +```sql +mysql> CREATE INDEX part_of_name ON titles (title(10)); +``` + +查看索引 + +```sql +mysql> show index from titles; ++--------+------------+--------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+ +| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment | Visible | Expression | ++--------+------------+--------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+ +| titles | 0 | PRIMARY | 1 | emp_no | A | 300519 | NULL | NULL | | BTREE | | | YES | NULL | +| titles | 0 | PRIMARY | 2 | title | A | 442783 | NULL | NULL | | BTREE | | | YES | NULL | +| titles | 0 | PRIMARY | 3 | from_date | A | 442783 | NULL | NULL | | BTREE | | | YES | NULL | +| titles | 1 | part_of_name | 1 | title | A | 6 | 10 | NULL | | BTREE | | | YES | NULL | ++--------+------------+--------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+ +4 rows in set (0.01 sec) +``` + +## 查看索引是否命中 + +索引创建后,可通过 [`explain`](https://github.com/wayou/wayou.github.io/issues/100) 语句分析查询是否命中索引。 + +```sql +mysql> EXPLAIN SELECT * FROM titles WHERE title = 'Engineer'; ++----+-------------+--------+------------+------+---------------+--------------+---------+-------+--------+----------+-----------------------+ +| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra | ++----+-------------+--------+------------+------+---------------+--------------+---------+-------+--------+----------+-----------------------+ +| 1 | SIMPLE | titles | NULL | ref | part_of_name | part_of_name | 42 | const | 221391 | 100.00 | Using index condition | ++----+-------------+--------+------------+------+---------------+--------------+---------+-------+--------+----------+-----------------------+ +1 row in set, 1 warning (0.01 sec) +``` + +其中 `possible_keys` 为可选的索引,`key` 为真实命中的索引。 + ## 相关资源