mysql> show index from test/G *************************** 1. row *************************** Table: test Non_unique: 0 Key_name: PRIMARY Seq_in_index: 1 Column_name: id Collation: A Cardinality: 4829778 Sub_part: NULL Packed: NULL Null: Index_type: BTREE Comment: Index_comment: *************************** 2. row *************************** Table: test Non_unique: 1 Key_name: idx_name1 Seq_in_index: 1 Column_name: name1 Collation: A Cardinality: 2414889 Sub_part: NULL Packed: NULL Null: YES Index_type: BTREE Comment: Index_comment: 2 rows in set (0.00 sec)
mysql> select count(*) from test; +----------+ | count(*) | +----------+ | 5000000 | +----------+ 1 row in set (1.59 sec) 基于name1进行like查询,耗时11.13s,从执行计划看,sql在执行时走的是全表扫描(type: ALL):
mysql> select * from test where name1 like '%O4JljqZw%'/G *************************** 1. row *************************** id: 1167352 name1: BO4JljqZws name2: BrfLU7J69j name3: XFikCVEilI name4: lr0yz3qMsO name5: vUUDghq8dx name6: RvQvSHHg4p name7: ESiDbQuK8f name8: GugFnLtYe8 name9: OuPwY8BsiY name10: O0oNGPX9IW 1 row in set (11.13 sec)
mysql> explain select * from test where name1 like '%O4JljqZw%'/G *************************** 1. row *************************** id: 1 select_type: SIMPLE table: test type: ALL possible_keys: NULL key: NULL key_len: NULL ref: NULL rows: 4829778 Extra: Using where 1 row in set (0.00 sec) 将sql改写为‘select a. from test a,(select id from test where name1 like '%O4JljqZw%') b where a.id=b.id;’ 提示优化器在子查询中使用二级索引idx_name1获取id:
mysql> select a.* from test a,(select id from test where name1 like '%O4JljqZw%') b where a.id=b.id/G *************************** 1. row *************************** id: 1167352 name1: BO4JljqZws name2: BrfLU7J69j name3: XFikCVEilI name4: lr0yz3qMsO name5: vUUDghq8dx name6: RvQvSHHg4p name7: ESiDbQuK8f name8: GugFnLtYe8 name9: OuPwY8BsiY name10: O0oNGPX9IW 1 row in set (2.46 sec)
mysql> explain select a.* from test a,(select id from test where name1 like '%O4JljqZw%') b where a.id=b.id/G *************************** 1. row *************************** id: 1 select_type: PRIMARY table: <derived2> type: ALL possible_keys: NULL key: NULL key_len: NULL ref: NULL rows: 4829778 Extra: NULL *************************** 2. row *************************** id: 1 select_type: PRIMARY table: a type: eq_ref possible_keys: PRIMARY key: PRIMARY key_len: 4 ref: b.id rows: 1 Extra: NULL *************************** 3. row *************************** id: 2 select_type: DERIVED table: test type: index possible_keys: NULL key: idx_name1 key_len: 63 ref: NULL rows: 4829778 Extra: Using where; Using index 3 rows in set (0.00 sec) 改写后的sql执行时间缩短至2.46s,效率提升了近4倍! 执行计划分析如下: step 1:mysql先对二级索引idx_name1进行覆盖扫描取出符合条件的id(Using where; Using index) step 2:对子step 1衍生出来的结果集table: <derived2>进行全表扫,获取id(本案例中只有一个id符合条件) step 3:最后根据step 2中的id使用主键回表获取数据(type: eq_ref,key: PRIMARY )