mysql唯一索引 覆盖索引

2021-03-03  本文已影响0人  matthewfly

当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。

select * from t where id>1 and name='y';

在5.6版本之前,只会匹配组合索引的id,后面的name不会走索引,命中id>1的每一项都会回表进行name=“y”的查询匹配。
5.6之后,mysql会优化sql往下推导,匹配索引name,减少回表次数。

上一篇 下一篇

猜你喜欢

热点阅读