MySQL 索引失效的几种场景
MySQL 索引 面试 评论 1 大约 2153 字模糊查询
模糊查询,头部模糊匹配。(尾部模糊匹配不会失效)
注意:如果覆盖索引能够使用,头部模糊查询也会走索引。
create table t_user(id int primary key, name varchar(25), age int, no int);
create index idx_age_name on t_user(age, name);
insert into t_user values(1, 'aaa', 10, 1), (2,'bbb', 20, 2), (3, 'ccc', 30, 3);
获取全部字段
explain select * from t_user where name like '%abc';
输出:
mysql> explain select * from t_user where name like '%abc';
+----+-------------+--------+------------+------+---------------+------+---------+------+------+----------+-------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+--------+------------+------+---------------+------+---------+------+------+----------+-------------+
| 1 | SIMPLE | t_user | NULL | ALL | NULL | NULL | NULL | NULL | 3 | 33.33 | Using where |
+----+-------------+--------+------------+------+---------------+------+---------+------+------+----------+-------------+
1 row in set, 1 warning (0.00 sec)
id
是主键,(age, name)
是联合索引。
利用覆盖索引,仅获取有索引的字段。
explain select id, age, name from t_user where name like '%abc';
输出:
mysql> explain select id, age, name from t_user where name like '%abc';
+----+-------------+--------+------------+-------+---------------+--------------+---------+------+------+----------+--------------------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+--------+------------+-------+---------------+--------------+---------+------+------+----------+--------------------------+
| 1 | SIMPLE | t_user | NULL | index | NULL | idx_age_name | 108 | NULL | 3 | 33.33 | Using where; Using index |
+----+-------------+--------+------------+-------+---------------+--------------+---------+------+------+----------+--------------------------+
1 row in set, 1 warning (0.00 sec)
使用函数
在索引列使用函数,如substring()
等。
联合索引
- 联合索引使用小于、大于(应使用小于等于、大于等于)
- 联合索引部分失效,
where
条件跳过了复合索引的部分
or
or
连接的条件,如果or
前面的字段有索引,or
后面的字段没有索引,也会使索引失效。
其他
- 字符串类型字段使用时不加引号
MySQL
评估使用索引比全表更慢,则不适用索引
阅读 1119 · 发布于 2022-05-12
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb扫描下方二维码关注公众号和小程序↓↓↓
昵称:
-
fHLvlxbf 1楼
e
Chrome | Windows 10 2023-07-24
随便看看
换一批
-
走进 Rust:结构体阅读 2635
-
Spring Boot Thymeleaf 国际化 i18n阅读 423
-
Webpack 相关知识点阅读 514
-
Safari 浏览器 white-space: pre 无效阅读 5389
-
OpenResty 使用 ngx.timer.every 完成定时任务阅读 8259
-
支付宝小程序使用 CSS 自定义智能客服组件的页面布局阅读 78
-
Spring Boot 集成 Flyway 数据库版本管理阅读 771
-
Java 中的反射阅读 1572
-
IDEA Endpoints 微服务工程中根据 URL 快速定位 Controller 类阅读 4114
-
Vue 重置 data 数据阅读 840