您使用的是哪個版本的MySQL?這是一個測試我的Percona服務器5.5.16上運行:
mysql> create table table_users (
id int auto_increment primary key,
fullname char(20),
username char(20),
unique key (fullname)
);
Query OK, 0 rows affected (0.03 sec)
mysql> insert into table_users values (default, 'billk', 'billk');
Query OK, 1 row affected (0.00 sec)
mysql> explain select * from table_users where fullname='billk'\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: table_users
type: const
possible_keys: fullname
key: fullname
key_len: 21
ref: const
rows: 1
Extra:
1 row in set (0.00 sec)
這表明它使用的全名索引,通過一個恆定值往上看,但它不是僅索引查詢。
mysql> explain select fullname from table_users where fullname='billk'\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: table_users
type: const
possible_keys: fullname
key: fullname
key_len: 21
ref: const
rows: 1
Extra: Using index
1 row in set (0.00 sec)
這是符合市場預期,這是能夠得到全名稱指數的全名欄,所以這是一個僅索引查詢。
mysql> explain select id from table_users where fullname='billk'\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: table_users
type: const
possible_keys: fullname
key: fullname
key_len: 21
ref: const
rows: 1
Extra: Using index
1 row in set (0.00 sec)
在搜索上全稱但取出的主鍵也僅索引的查詢,因爲InnoDB二級索引的(例如,唯一密鑰)的葉節點隱含包含主鍵值。所以這個查詢能夠遍歷BTREE的全名,作爲獎勵,它也得到了ID。
mysql> explain select fullname, username from table_users where fullname='billk'\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: table_users
type: const
possible_keys: fullname
key: fullname
key_len: 21
ref: const
rows: 1
Extra:
1 row in set (0.00 sec)
只要選擇列表包含任何不屬於索引的列,它就不能再是僅索引查詢。首先搜索BTREE的全名,找到主鍵值。然後它使用該id值遍歷聚集索引的BTREE,這是InnoDB如何存儲整個表。在那裏它找到給定行的其他列,包括用戶名。
謝謝,所以基本上我的索引應該沒問題,額外的只是告訴我它是否可以使用索引返回結果,或者是否需要真正在表中搜索它? – Jeff
對。你所要求的所有數據都在索引本身 –