[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 |
+----+-------------+-------+------+---------------+------+---------+-------+------+-------------+

 


免責聲明!

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



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