對于mysql建表稍有點經驗的開發人員都會為后續的where查詢條件提前考慮創建索引,
這里說的是在使用索引查詢時有關索引下推的有關知識點,
綜合前人的經驗結果:索引下推是資料庫檢索資料程序中為減少回表次數而做的優化,
判斷是否需要回表的是由mysql存盤引擎控制,默認從mysql5.6版本開始支持,
下面用docker分別創建基于mysql5.5和mysql5.6的容器,表結構保持一致(docker創建mysql容器不做演示),
首先看mysql5.5:
mysql> select version();
+-----------+
| version() |
+-----------+
| 5.5.62 |
+-----------+
1 row in set (0.00 sec)
mysql> show create table testhh\G;
*************************** 1. row ***************************
Table: testhh
Create Table: CREATE TABLE `testhh` (
`id` int(10) unsigned NOT NULL,
`age` int(10) unsigned DEFAULT '0',
`name` char(10) NOT NULL DEFAULT '',
`height` int(10) NOT NULL DEFAULT '0',
`name2` char(10) NOT NULL DEFAULT '',
`height2` int(10) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `age_index` (`age`) USING HASH,
KEY `un` (`name`,`height`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
1 row in set (0.00 sec)
ERROR:
No query specified
mysql> explain select * from testhh where name like 'a%' and height = 100\G;
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: testhh
type: range
possible_keys: un
key: un
key_len: 14
ref: NULL
rows: 1
Extra: Using where
1 row in set (0.00 sec)
ERROR:
No query specified
上面可見explain的extra欄位結果時Using where,表示優化器需要通過索引回表查詢資料,
再看mysql5.6:
mysql> select version(); +-----------+ | version() | +-----------+ | 5.6.50 | +-----------+ 1 row in set (0.00 sec) mysql> show create table ua\G; *************************** 1. row *************************** Table: ua Create Table: CREATE TABLE `ua` ( `id` int(10) NOT NULL AUTO_INCREMENT, `name` char(10) NOT NULL DEFAULT '', `height` int(10) NOT NULL DEFAULT '0', `name2` char(10) NOT NULL DEFAULT '', `height2` int(10) NOT NULL DEFAULT '0', PRIMARY KEY (`id`), KEY `nh` (`name`,`height`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 1 row in set (0.00 sec) ERROR: No query specified mysql> explain select * from ua where name like 'a%' and height=10\G; *************************** 1. row *************************** id: 1 select_type: SIMPLE table: ua type: range possible_keys: nh key: nh key_len: 14 ref: NULL rows: 1 Extra: Using index condition 1 row in set (0.00 sec) ERROR: No query specified
explain的extra欄位是Using index condition,表示會先通過條件過濾索引,再通過過濾后的索引查詢符合索引條件的資料,
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/237955.html
標籤:其他
