0
点赞
收藏
分享

微信扫一扫

MySQL索引条件下推优化案例

索引条件下推优化意思是:存储引擎使用索引从表中获取数据,而不是存储引擎会遍历索引来查找表中的行,并将其返回给 MySQL 服务器,由服务器进行WHERE查找。 官方原文如下:

定义:Index Condition Pushdown (ICP) is an optimization for the case where MySQL retrieves rows from a table using an index. Without ICP, the storage engine traverses the index to locate rows in the base table and returns them to the MySQL server which evaluates the WHERE condition for the rows. With ICP enabled, and if parts of the WHERE condition can be evaluated by using only columns from the index, the MySQL server pushes this part of the WHERE condition down to the storage engine. The storage engine then evaluates the pushed index condition by using the index entry and only if this is satisfied is the row read from the table. 好处:ICP can reduce the number of times the storage engine must access the base table and the number of times the MySQL server must access the storage engine.



MySQL表结构如下:
```sql
CREATE TABLE `t1` (
  `c1` int DEFAULT NULL,
  `c2` int DEFAULT NULL,
  `c3` int NOT NULL,
  `c4` int DEFAULT NULL,
  KEY `idx` (`c1`,`c2`,`c3`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3

查询1

SELECT * FROM t1 where c1=1 and c2=1;

image.png

命中了索引idx,使用了c1和c2列索引。

查询2

SELECT * FROM t1 where c1=1 and c3=1;

image.png

命中了索引idx,但是只使用了c1列索引,但是使用了索引条件下推优化。

如图,在存储引擎层过滤数据,直接返回给MySQL Server,而不是MySQL Server获取到C1=1后来过滤C3=1。

image.png

查询3

SELECT * FROM t1 where c2=1 and c3=1;

image.png 没有使用索引,进行了全表扫描。通过Using where来进行过滤。

查询4

SELECT * FROM t1 where c1=1 or c2=1;

image.png 没有使用索引,进行了全表扫描。通过Using where来进行过滤。

参考文档

https://dev.mysql.com/doc/refman/8.0/en/index-condition-pushdown-optimization.html

举报

相关推荐

0 条评论