查看explain中的key_len判斷究竟使用了哪個索引?
在一張表裡有多個索引, 我們where欄位裡條件有多個索引的值, 那麼究竟使用的哪一個呢?
推薦:《 mysql影片教學》
我們可以用explain來查看, 其中的key_len欄位可以看得出來
例如下面這本sql
explain select * from ent_calendar_diary where email='xxxx' and diary_id=1784; +----+-------------+--------------------+------------+-------+-------------------------+---------+---------+-------+------+----------+-------+ | id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra | +----+-------------+--------------------+------------+-------+-------------------------+---------+---------+-------+------+----------+-------+ | 1 | SIMPLE | ent_calendar_diary | NULL | const | PRIMARY,idx_email_stime | PRIMARY | 4 | const | 1 | 100.00 | NULL | +----+-------------+--------------------+------------+-------+-------------------------+---------+---------+-------+------+----------+-------+
possible_keys裡面有兩個索引欄位, 但是看key_len 是4個位元組
備註,key_len 只指示了WHERE中用於條件過濾時被選中的索引列,是不包含ORDER BY/GROUP BY
int類型並且not null 是4個位元組, 因此上面的sql是使用的主鍵索引
explain select * from ent_calendar_diary where email='xxxx'; +----+-------------+--------------------+------------+------+-----------------+-----------------+---------+-------+------+----------+-------+ | id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra | +----+-------------+--------------------+------------+------+-----------------+-----------------+---------+-------+------+----------+-------+ | 1 | SIMPLE | ent_calendar_diary | NULL | ref | idx_email_stime | idx_email_stime | 767 | const | 111 | 100.00 | NULL | +----+-------------+--------------------+------------+------+-----------------+-----------------+---------+-------+------+----------+-------+
這個是767個字節, varchar(255) not null 255 * 3 2剛好符合, 因此是使用的email
# ###CREATE TABLE `ent_calendar_diary` ( `diary_id` int(10) unsigned NOT NULL AUTO_INCREMENT, `email` varchar(255) NOT NULL, `title` varchar(100) NOT NULL, `summary` varchar(500) NOT NULL DEFAULT '', `stime` bigint(11) NOT NULL DEFAULT '0', `ctime` int(10) unsigned NOT NULL DEFAULT '0', PRIMARY KEY (`diary_id`), KEY `idx_email_stime` (`email`,`stime`) ) ENGINE=InnoDB AUTO_INCREMENT=1809 DEFAULT CHARSET=utf8
以上是查看explain中的key_len判斷究竟用了哪個索引的詳細內容。更多資訊請關注PHP中文網其他相關文章!