Skip to content

Commit

Permalink
Add new comment
Browse files Browse the repository at this point in the history
  • Loading branch information
wayou committed Apr 22, 2024
1 parent 612f101 commit 32bf777
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions _posts/2019-05-09-MySQL_中的索引.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` 为真实命中的索引。


## 相关资源

Expand Down

0 comments on commit 32bf777

Please sign in to comment.