1. 程式人生 > 實用技巧 >[MySQL] 利用explain檢視sql語句中使用的哪個索引

[MySQL] 利用explain檢視sql語句中使用的哪個索引

欄位型別是:
`enterpriseId` int(10) unsigned DEFAULT NULL,
`email` char(255) NOT NULL DEFAULT '',
表的索引是:
UNIQUE KEY `emailent` (`email`,`enterpriseId`),
KEY `edf` (`enterpriseId`,`departId`,`flag`),

有這麼兩條sql語句,分別表現是:

explain select email from email where enterpriseId=23684 and (email like 'aaa%');
+----+-------------+-------+------+---------------+------+---------+-------+------+-------------+
| id | select_type | table | type | possible_keys | key  | key_len | ref
| rows | Extra | +----+-------------+-------+------+---------------+------+---------+-------+------+-------------+ | 1 | SIMPLE | email | ref | emailent,edf | edf | 5 | const | 6 | Using where |


看到key_len的長度是5 ,可以知道使用的是edf這個索引 , 因為edf索引中的enterpriseId是int型別4個位元組 ,預設null 加1個位元組,總共5個位元組

也就是先使用enterpriseId查到索引,在索引中使用where過濾資料

explain select email from email where enterpriseId=23684 and (email like 'aaas%');
+----+-------------+-------+-------+---------------+----------+---------+------+------+--------------------------+
| id | select_type | table | type  | possible_keys | key      | key_len | ref
| rows | Extra | +----+-------------+-------+-------+---------------+----------+---------+------+------+--------------------------+ | 1 | SIMPLE | email | range | emailent,edf | emailent | 770 | NULL | 2 | Using where; Using index | +----+-------------+-------+-------+---------------+----------+---------+------+------+--------------------------+


在like的時候比上面多了一個字元,這個時候的索引情況是key_len是770,可以知道使用的是emailent這個索引,因為這個的索引長度是
255*3+5=770 varchar是255個字元,utf8下是*3, 加上int 5個位元組

like兩邊都有%的情況,只會使用第一個條件的edf索引

mysql> explain select * from email where enterpriseId=23684 and (email like '%shihanasas%');
+----+-------------+-------+------+---------------+------+---------+-------+------+-------------+
| id | select_type | table | type | possible_keys | key  | key_len | ref   | rows | Extra       |
+----+-------------+-------+------+---------------+------+---------+-------+------+-------------+
|  1 | SIMPLE      | email | ref  | edf           | edf  | 5       | const |    6 | Using where |
+----+-------------+-------+------+---------------+------+---------+-------+------+-------------+