mysql使用索引下推的好处_mysql的索引下推理解和实践
對于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> 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,表示會先通過條件過濾索引,再通過過濾后的索引查詢符合索引條件的數據。
總結
以上是生活随笔為你收集整理的mysql使用索引下推的好处_mysql的索引下推理解和实践的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: STL和FIG文件的结构
- 下一篇: 新建文件夹快捷键