mysql使用索引下推的好处_mysql的索引下推理解和实践
對于mysql建表稍有點經(jīng)驗的開發(fā)人員都會為后續(xù)的where查詢條件提前考慮創(chuàng)建索引。
這里說的是在使用索引查詢時有關(guān)索引下推的有關(guān)知識點。
綜合前人的經(jīng)驗結(jié)果:索引下推是數(shù)據(jù)庫檢索數(shù)據(jù)過程中為減少回表次數(shù)而做的優(yōu)化。
判斷是否需要回表的是由mysql存儲引擎控制,默認從mysql5.6版本開始支持。
下面用docker分別創(chuàng)建基于mysql5.5和mysql5.6的容器,表結(jié)構(gòu)保持一致(docker創(chuàng)建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字段結(jié)果時Using where,表示優(yōu)化器需要通過索引回表查詢數(shù)據(jù)。
再看mysql5.6:
mysql> selectversion();+-----------+
| version() |
+-----------+
| 5.6.50 |
+-----------+
1 row in set (0.00sec)
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=latin11 row in set (0.00sec)
ERROR:
No query specified
mysql> explain select * from ua where name like 'a%' and height=10\G;*************************** 1. row ***************************id:1select_type: SIMPLE
table: ua
type: range
possible_keys: nh
key: nh
key_len:14
ref: NULL
rows:1Extra: Using index condition1 row in set (0.00sec)
ERROR:
No query specified
explain的extra字段是Using index condition,表示會先通過條件過濾索引,再通過過濾后的索引查詢符合索引條件的數(shù)據(jù)。
總結(jié)
以上是生活随笔為你收集整理的mysql使用索引下推的好处_mysql的索引下推理解和实践的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: STL和FIG文件的结构
- 下一篇: mysql数据库熟悉表空间数据文件_Or