MySQL 的索引是如何工作的?10 分鐘講清楚!
閱讀本文大概需要 5.5 分鐘。
一、前言
二、知識補充
一般地,key_len 等于索引列類型字節(jié)長度,例如int類型為4 bytes,bigint為8 bytes;
如果是字符串類型,還需要同時考慮字符集因素,例如:CHAR(30) UTF8則key_len至少是90 bytes;
若該列類型定義時允許NULL,其key_len還需要再加 1 bytes;
若該列類型為變長類型,例如 VARCHAR(TEXT\BLOB不允許整列創(chuàng)建索引,如果創(chuàng)建部分索引也被視為動態(tài)列類型),其key_len還需要再加 2 bytes;
三、哪些條件能用到索引
exp:idx_c1_c2_c3(c1,c2,c3)where c1>=1 and c2>2 and c3=1first key (c1,c2)c1為 '>=' ,加入下邊界界定,繼續(xù)匹配下一個c2 為 '>',加入下邊界界定,停止匹配
exp:idx_c1_c2_c3(c1,c2,c3)where c1<=1 and c2=2 and c3<3last key (c1,c2,c3)c1為 '<=',加入上邊界界定,繼續(xù)匹配下一個c2為 '='加入上邊界界定,繼續(xù)匹配下一個c3 為 '<',加入上邊界界定,停止匹配
注:這里簡單的記憶是,如果比較符號中包含'='號,'>='也是包含'=',那么該索引鍵是可以被利用的,可以繼續(xù)匹配后面的索引鍵值;如果不存在'=',也就是'>','<',這兩個,后面的索引鍵值就無法匹配了。同時,上下邊界是不可以混用的,哪個邊界能利用索引的的鍵值多,就是最終能夠利用索引鍵值的個數(shù)。
Index Filter
exp:idex_c1_c2_c3where c1>=1 and c2<=2 and c3 =1index key --> c1index filter--> c2 c3
Table Filter
四、Between 和Like 的處理
Between
Like
五、索引的排序
Make sure it uses index It is very important to have ORDER BY with LIMIT executed without scanning and sorting full result set, so it is important for it to use index – in this case index range scan will be started and query execution stopped as soon as soon as required amount of rows generated.
CREATE TABLE `t1` (`id` int(11) NOT NULL AUTO_INCREMENT,`c1` int(11) NOT NULL DEFAULT '0',`c2` int(11) NOT NULL DEFAULT '0',`c3` int(11) NOT NULL DEFAULT '0',`c4` int(11) NOT NULL DEFAULT '0',`c5` int(11) NOT NULL DEFAULT '0',PRIMARY KEY (`id`),KEY `idx_c1_c2_c3` (`c1`,`c2`,`c3`)) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8mb4select * from t1;+----+----+----+----+----+----+| id | c1 | c2 | c3 | c4 | c5 |+----+----+----+----+----+----+| 1 | 3 | 3 | 2 | 0 | 0 || 2 | 2 | 4 | 5 | 0 | 0 || 3 | 3 | 2 | 4 | 0 | 0 || 4 | 1 | 3 | 2 | 0 | 0 || 5 | 1 | 3 | 3 | 0 | 0 || 6 | 2 | 3 | 5 | 0 | 0 || 7 | 3 | 2 | 6 | 0 | 0 |+----+----+----+----+----+----+7 rows in set (0.00 sec)select c1,c2,c3 from t1;+----+----+----+| c1 | c2 | c3 |+----+----+----+| 1 | 3 | 2 || 1 | 3 | 3 || 2 | 3 | 5 || 2 | 4 | 5 || 3 | 2 | 4 || 3 | 2 | 6 || 3 | 3 | 2 |+----+----+----+7 rows in set (0.00 sec)
存在一張表,c1,c2,c3上面有索引,select c1,c2,c3 from t1;?查詢走的是索引全掃描,因此呈現(xiàn)的數(shù)據(jù)相當于在沒有索引的情況下select c1,c2,c3 from t1 order by c1,c2,c3;?的結(jié)果。
c1=3,c2=2 — > c3 有序
c1 in(1,2) —> c2 無序 ,c3 無序
有個小規(guī)律,idx_c1_c2_c3,那么如何確定某個字段是有序的呢?c1 在索引的最前面,肯定是有序的,c2在第二個位置,只有在c1 唯一確定一個值的時候,c2才是有序的,如果c1有多個值,那么c2 將不一定有序,同理,c3也是類似
六、小結(jié)
推薦閱讀:
SpringCloud中Zuul網(wǎng)關(guān)原理及其配置,看它就夠了!
微信掃描二維碼,關(guān)注我的公眾號
朕已閱?
評論
圖片
表情

