場景
不少人可能在使用Navicat給表建立索引時會發現,索引方法中支持BTREE和HASH
html
![](http://static.javashuo.com/static/loading.gif)
乍一看,不少人的第一反應是,這不是支持hash索引嗎?
實踐
那麼咱們來實踐一下。java
CREATE TABLE `auth_user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主鍵',
`username` varchar(20) DEFAULT NULL COMMENT '用戶名',
`password` varchar(20) DEFAULT NULL COMMENT '密碼',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4;
![](http://static.javashuo.com/static/loading.gif)
對應sql語句:
mysql
ALTER TABLE oauth.auth_user ADD INDEX index1(username) USING HASH COMMENT '測試hash索引';
保存成功,表的DML語句變爲:web
CREATE TABLE `auth_user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主鍵',
`username` varchar(20) DEFAULT NULL COMMENT '用戶名',
`password` varchar(20) DEFAULT NULL COMMENT '密碼',
PRIMARY KEY (`id`),
KEY `index1` (`username`) USING HASH COMMENT '測試hash索引'
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4;
不少人可能會馬上說,這不是建立成功了嗎?面試
咱們繼續,從新打開數據庫鏈接,打開表設計,會發現index1索引的索引方法變成了btree,
sql
![](http://static.javashuo.com/static/loading.gif)
可是表定義語句仍是沒有變化,數據庫
CREATE TABLE `auth_user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主鍵',
`username` varchar(20) DEFAULT NULL COMMENT '用戶名',
`password` varchar(20) DEFAULT NULL COMMENT '密碼',
PRIMARY KEY (`id`),
KEY `index1` (`username`) USING HASH COMMENT '測試hash索引'
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4;
那麼這時,索引index1究竟是btree索引仍是hash索引呢?
經過命令查看錶auth上的索引信息微信
show index from auth_user;
![](http://static.javashuo.com/static/loading.gif)
發現主鍵索引和index1索引的index_type都是btree,說明建立的hash索引是沒有生效的。
分析:
查一下mysql官方文檔:https://dev.mysql.com/doc/refman/5.7/en/create-index.html,app
![](http://static.javashuo.com/static/loading.gif)
我們具體查一下InnoDB文檔那一部分:https://dev.mysql.com/doc/refman/5.7/en/innodb-introduction.html。
性能
![](http://static.javashuo.com/static/loading.gif)
能夠發現InnoDB支持的全部特性,其中對Hash index特徵的支持描述是:
No (InnoDB utilizes hash indexes internally for its Adaptive Hash Index feature.)
翻譯過來:
不支持(InnoDB在內部利用hash索引來實現其自適應hash索引特性)
那麼什麼是Adaptive Hash Index呢?
![](http://static.javashuo.com/static/loading.gif)
根據文件,不難發現,自適應索引是InnoDB引擎的內存結構中的一種特性。
對自適應hash索引的描述:
自適應hash索引特性使InnoDB可以在具備適當的工做負載和足夠的緩衝池內存的系統上執行更像內存中的數據庫,而不犧牲事務特性或可靠性。
總的來講就是提升了查詢性能。
那麼怎樣啓動自適應hash索引的特性呢?
14.15 InnoDB Startup Options and System Variables
System variables that are true or false can be enabled at server startup by naming them, or disabled by using a --skip- prefix. For example, to enable or disable the InnoDB adaptive hash index, you can use --innodb-adaptive-hash-index or --skip-innodb-adaptive-hash-index on the command line, or innodb_adaptive_hash_index or skip_innodb_adaptive_hash_index in an option file.
翻譯過來就是能夠在啓動命令中,加上--innodb-adaptive-hash-index就能夠開啓InnoDB 自適應索引的特性了。
其實【MySQL技術內幕InnoDB存儲引擎.姜承堯.掃描版】也提到了這點
![](http://static.javashuo.com/static/loading.gif)
總結:
Mysql InnoDB引擎不支持hash索引,可是在內存結構中有一個自適應hash索引,來提升查詢性能。
多看,多思,多實踐,多記錄,多交流,老萬教你吊打面試官。
更多精彩,關注我吧。
本文分享自微信公衆號 - 跟着老萬學java(douzhe_2019)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。