Index Condition Pushdown (ICP)是MySQL 5.6 版本中的新特性,是一种在存储引擎层使用索引过滤数据的一种优化方式。mysql
优化效果:ICP能减小引擎层访问基表的次数和MySQL Server 访问存储引擎的次数,减小io次数,提升查询语句性能。sql
mysql> show create table user\G
*************************** 1. row ***************************
Table: user
Create Table: CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL,
`password` varchar(50) NOT NULL,
`score` smallint(3) NOT NULL,
`mobile` char(11) NOT NULL DEFAULT '',
PRIMARY KEY (`id`),
KEY `unique_username` (`username`),
KEY `pre_idx` (`score`,`mobile`,`username`)
) ENGINE=InnoDB AUTO_INCREMENT=200003 DEFAULT CHARSET=utf8
1 row in set (0.00 sec)服务器
mysql> set optimizer_switch="index_condition_pushdown=on";性能
mysql> explain select * from user where score=60 and mobile like '%75%' and username like '%username11%'\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: user
partitions: NULL
type: ref
possible_keys: pre_idx
key: pre_idx
key_len: 2
ref: const
rows: 2012
filtered: 1.23
Extra: Using index condition
1 row in set, 1 warning (0.00 sec)优化
从explain 着灰底色的参数能够看到,使用了复合索引 pre_idx,而且只使用了 score字段的索引(由于mobile 与 username 使用了模糊查询,没法使用索引),但Extra列并无Using where,而是Using index condition,说明使用了ICP,在存储引擎使用了索引过滤where条件,再也不把经过索引查找到的数据传输到mysql服务器层经过where条件过滤。
spa
mysql> set optimizer_switch="index_condition_pushdown=off";server
mysql> explain select * from user where score=60 and mobile like '%75%' and username like '%username11%'\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: user
partitions: NULL
type: ref
possible_keys: pre_idx
key: pre_idx
key_len: 2
ref: const
rows: 2012
filtered: 1.23
Extra: Using where
1 row in set, 1 warning (0.00 sec)blog
从explain 着灰底色的参数能够看到,使用了复合索引 pre_idx,而且只使用了 score字段的索引(由于mobile 与 username 使用了模糊查询,没法使用索引),Extra出现Using where。索引
从案例能够看到,当开启ICP时 查询在sending data环节时间消耗是 0.006537s,未开启时是0.329598s,如今该表的数据量为20w,差别已经很是明显了。it