【发布时间】:2020-02-09 12:42:01
【问题描述】:
覆盖索引是 InnoDB 中索引的一种特殊情况,其中查询的所有必需字段都包含在索引中,如本博客 https://blog.toadworld.com/2017/04/06/speed-up-your-queries-using-the-covering-index-in-mysql 中所述。
但是,我遇到了一种情况,当 SELECT 和 WHERE 只包含索引列或主键时,没有使用覆盖索引。
MySQL 版本:5.7.27
示例表:
mysql> SHOW CREATE TABLE employees.employees\G;
*************************** 1. row ***************************
Table: employees
Create Table: CREATE TABLE `employees` (
`emp_no` int(11) NOT NULL,
`birth_date` date NOT NULL,
`first_name` varchar(14) NOT NULL,
`last_name` varchar(16) NOT NULL,
`gender` enum('M','F') NOT NULL,
`hire_date` date NOT NULL,
PRIMARY KEY (`emp_no`),
KEY `first_name_last_name` (`first_name`,`last_name`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
行数:300024
索引:
mysql> SHOW INDEX FROM employees.employees;
+-----------+------------+----------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+-----------+------------+----------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| employees | 0 | PRIMARY | 1 | emp_no | A | 299379 | NULL | NULL | | BTREE | | |
| employees | 1 | first_name_last_name | 1 | first_name | A | 1242 | NULL | NULL | | BTREE | | |
| employees | 1 | first_name_last_name | 2 | last_name | A | 276690 | NULL | NULL | | BTREE | | |
+-----------+------------+----------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
mysql> EXPLAIN SELECT first_name, last_name FROM employees.employees WHERE emp_no < '10010';
+----+-------------+-----------+------------+-------+---------------+---------+---------+------+------+----------+-------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+-----------+------------+-------+---------------+---------+---------+------+------+----------+-------------+
| 1 | SIMPLE | employees | NULL | range | PRIMARY | PRIMARY | 4 | NULL | 9 | 100.00 | Using where |
+----+-------------+-----------+------------+-------+---------------+---------+---------+------+------+----------+-------------+
1 row in set, 1 warning (0.00 sec)
可以看出,SELECT子句中的first_name和last_name是索引列,WHERE子句中的emp_no是主键。但是,执行计划显示结果行是从主索引树中检索的。
在我看来,它应该扫描二级索引树,并通过emp_no < '10010'过滤结果,其中使用了覆盖索引。
编辑
另外,我看到在 MySQL 5.7.21 下同样的情况下使用了覆盖索引。
行数:8204
SQL:
explain select poi_id , ctime from another_table where id < 1000;
【问题讨论】:
标签: mysql sql non-clustered-index covering-index