900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > MySQL数据库模糊查询什么时候可以使用到索引

MySQL数据库模糊查询什么时候可以使用到索引

时间:2021-05-17 00:12:09

相关推荐

MySQL数据库模糊查询什么时候可以使用到索引

正常情况下,当使用模糊查询字段,例如like “%hh”,%开头的查询时是没办法使用索引的,但是使用like “kk%” 模糊字段在后面的也是可以使用索引的。

特殊情况:当所需要查询的字段是属于已建的索引时(包括主键索引),那么这时候即使是以%开头的字段,依旧可以使用索引其本质原因是对于非聚簇索引,这里有一个覆盖查询的操作,即当查询的字段全部属于建立索引字段时,非聚簇索引不需要进行“回表”,即不需要再去主键索引(聚簇索引)里面进行进一步的查询

实例:

# 对student_info 表格的 name字段建立stuname索引,且id为主键索引mysql> select * from student_info;+----+--------+--------+| id | name | gender |+----+--------+--------+| 1 | Kate |2 || 2 | Mary |2 || 3 | Tom |1 || 4 | Jim |1 || 5 | Lily |2 || 6 | Rose |2 || 7 | Lucy |2 || 8 | Meimei |2 |+----+--------+--------+8 rows in set (0.00 sec)mysql> explain select name from student_info where id like "%m"; +----+-------------+--------------+-------+---------------+---------+---------+------+------+--------------------------+| id | select_type | table | type | possible_keys | key| key_len | ref | rows | Extra|+----+-------------+--------------+-------+---------------+---------+---------+------+------+--------------------------+| 1 | SIMPLE| student_info | index | NULL| stuname | 123| NULL | 8 | Using where; Using index |+----+-------------+--------------+-------+---------------+---------+---------+------+------+--------------------------+1 row in set (0.00 sec)# 这里只查找name,可以看到,它使用了stuname索引mysql> explain select id,name from student_info where id like "%m"; +----+-------------+--------------+-------+---------------+---------+---------+------+------+--------------------------+| id | select_type | table | type | possible_keys | key| key_len | ref | rows | Extra|+----+-------------+--------------+-------+---------------+---------+---------+------+------+--------------------------+| 1 | SIMPLE| student_info | index | NULL| stuname | 123| NULL | 8 | Using where; Using index |+----+-------------+--------------+-------+---------------+---------+---------+------+------+--------------------------+1 row in set (0.00 sec)# 这里查询了name和id,可以看到也是使用了索引的mysql> explain select id,name,gender from student_info where id like "%m"; +----+-------------+--------------+------+---------------+------+---------+------+------+-------------+| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |+----+-------------+--------------+------+---------------+------+---------+------+------+-------------+| 1 | SIMPLE| student_info | ALL | NULL| NULL | NULL | NULL | 8 | Using where |+----+-------------+--------------+------+---------------+------+---------+------+------+-------------+1 row in set (0.00 sec)# 这里查询了非索引字段gender,发现其并没有使用索引。

综上可知,由于覆盖索引机制的存在,当我们查询的字段是属于索引字段时,那么就不需要进行“回表”操作,即使是以“%”开头的模糊查询,依旧可使用索引;

注:

对于联合索引,同样符合这个机制,且由于联合索引同时存储多个字段,相比于只使用一个字段的单键索引,它的覆盖机制出现的可能性也更高一些。从索引优化的角度来看,这也是为什么一直强调非必要不使用select * 的原因,因为你只查询自己需要的字段的话,很多情况下是可以借助索引默认提高查找效率的。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。