聊聊Hash索引


hash index是基於哈希表實現的,只有精確匹配索引所有列的查詢才會生效。對於每一行數據,存儲引擎都會對所有的索引列計算一個hash code,並將的有的hash code存儲在索引中,同時在哈希表中保存指向每個數據行的指針。

在MySQL中,只有Memory引擎顯示支持哈希索引,也是默認索引類型。

如:

create table test_hash(

fname varchar(50) not null,

lname varchar(50) not null,

key using hash(fname)

)engine=memory;

mysql>select * from test_hash;

fname  |  lname

Peter   |  Andyxi

mysql>select lname from test_hash where fname='Peter';

過程:

1.MySQL先計算‘Peter’的哈希值,並使用該值尋找對應的記錄指針

2.通過指針找到對應的行的值

Hash Index注意點:

1.只包含哈希值和指針,而不存儲字段值。

2.存儲不是執照索引值順序的,無法用於排序。

3.不支持部分索引列匹配,因為始終是使用索引列的全部內容來計算哈希值的。

4.只支持等值比較查詢。

案例:存儲大量的URL,並需要根據URL進行搜索查找。

mysql>select id from url where url="http://www.mysql.com";

mysql> create table pseudohash(
-> id int unsigned not null auto_increment,
-> url varchar(255) not null,
-> url_crc int unsigned not null default 0,
-> primary key(id));
Query OK, 0 rows affected (0.72 sec)

可以通過觸發器在插入和更新時維護url_cc列。

mysql> delimiter //
mysql> create trigger pseudohash_crc_ins before insert on pseudohash for each row begin set new.url_crc=crc32(new.url);
-> end;
-> //
Query OK, 0 rows affected (0.02 sec)

mysql> create trigger pseudohash_crc_upd before update on pseudohash for each row begin set new.url_crc=crc32(new.url);
-> end;
-> //
Query OK, 0 rows affected (0.01 sec)

mysql> delimiter;

mysql> select * from pseudohash;
Empty set (0.00 sec)

mysql> insert into pseudohash(url) values('http://www.mysql.com');
Query OK, 1 row affected (0.00 sec)

mysql> select * from pseudohash;
+----+----------------------+------------+
| id | url | url_crc |
+----+----------------------+------------+
| 1 | http://www.mysql.com | 1560514994 |
+----+----------------------+------------+

mysql> update pseudohash set url="http://www.mysql.com/" where id=1;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0

mysql> select * from pseudohash;
+----+-----------------------+------------+
| id | url | url_crc |
+----+-----------------------+------------+
| 1 | http://www.mysql.com/ | 1558250469 |
+----+-----------------------+------------+
1 row in set (0.00 sec)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM