當(dāng)mysql唯一索引是組合索引時,如果查詢條件滿足組合索引的覆蓋條件,同樣將是覆蓋索引。
測試:
新建表t:
mysql> desc t;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id | bigint | YES | MUL | NULL | |
| name | varchar(20) | YES | MUL | NULL | |
| type | int | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
添加唯一索引:
alter table t add unique index test_unique(id,name,type);
explain select * from t where id=1 and name='y';查看索引使用情況:
+----+-------------+-------+------------+------+---------------+-------------+---------+-------------+------+----------+-------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+-------+------------+------+---------------+-------------+---------+-------------+------+----------+-------------+
| 1 | SIMPLE | t | NULL | ref | test_unique | test_unique | 92 | const,const | 1 | 100.00 | Using index |
+----+-------------+-------+------------+------+---------------+-------------+---------+-------------+------+----------+-------------+
1 row in set, 1 warning (0.00 sec)
可以看到使用了索引test_unique。
- 索引下推
mysql5.6之前,當(dāng)遇到第一個范圍查詢語句時就停止了組合索引的匹配。例如上面表中有組合索引(id,name,type),此時執(zhí)行
select * from t where id>1 and name='y';
在5.6版本之前,只會匹配組合索引的id,后面的name不會走索引,命中id>1的每一項(xiàng)都會回表進(jìn)行name=“y”的查詢匹配。
5.6之后,mysql會優(yōu)化sql往下推導(dǎo),匹配索引name,減少回表次數(shù)。