索引小剧场:某日,程序员小明发现sql查询突然从0.1秒暴增到5秒。索引委屈巴巴:“主人,不是我不干活,是你老给我穿小鞋啊!”
一、索引:数据库世界的超级目录
索引如同图书馆的图书目录:
- 聚簇索引:书架按编号排序(数据即索引)
- 二级索引:独立目录卡片(需回表查询)
- b+树结构:多叉平衡树,3层可存2000万数据(假设每页16kb)
// java中创建索引示例(spring data jpa) @entity @table(indexes = @index(columnlist = "username,email", name = "idx_user_identity")) public class user { @id private long id; private string username; // 索引列 private string email; // 索引列 private integer age; // getter/setter省略 }
二、索引罢工的五大罪状(失效场景)
1.最左匹配原则
-- 创建联合索引 create index idx_soldier on army(squad, team, soldier); -- 有效查询 ✅ select * from army where squad = 'a'; select * from army where squad = 'a' and team = 2; -- 索引罢工 ❌ select * from army where team = 2; -- 跳过squad select * from army where soldier = 'tom'; -- 跳过头两列
原理:联合索引如电话簿,必须先按省→市→姓名查找,跳级查询无效
2.隐式转换
// java代码中常见的类型错误 @query("select u from user u where u.username = :name") // username是varchar user findbyusername(@param("name") integer name); // 传入integer类型!
执行sql:
select * from user where username = 100; -- 类型转换导致:username列索引失效!
原理:mysql被迫对索引列做类型转换(cast),如同要求目录同时支持字母和数字排序
3.函数计算
-- 生日字段有索引 select * from user where year(birthday) = 1990; -- 索引失效 ❌ -- 优化方案 ✅ select * from user where birthday between '1990-01-01' and '1990-12-31';
血泪案例:某电商平台因date(create_time)
查询导致cpu飙升90%
4.范围查询阻断连锁反应
create index idx_sales on orders(region, amount, product); -- 索引仅用到 region 和 amount ❌ select * from orders where region = 'east' and amount > 1000 and product = 'phone';
破解方案:调整索引顺序为(region, product, amount)
5.or引发的危机
-- 即使name和age都有独立索引 select * from user where name = 'john' or age = 30; -- mysql通常选择全表扫描!
优化方案:改用union
select * from user where name = 'john' union all select * from user where age = 30;
三、原理深潜:b+树为何罢工
当发生索引失效时:
- 优化器计算使用索引的成本
- 若预计扫描超过30%数据(默认阈值)
- 选择全表扫描作为“更优方案”
冷知识:force index
可强制使用索引,但如同用枪逼工人干活,慎用!
四、避坑指南:四大生存法则
前缀索引策略
alter table article add index idx_title(title(10));
对长文本取前n个字符(需保证区分度>90%)
覆盖索引护盾
-- 建立覆盖索引 create index idx_covering on orders(user_id, status, amount); -- 查询只需索引列 select user_id, status from orders where user_id = 1001;
索引下推(icp)
mysql 5.6+ 黑科技:
在存储引擎层提前过滤数据
索引散兵清理
-- 每月检查无用索引 select * from sys.schema_unused_indexes;
五、最佳实践:索引优化军规
场景 | 错误做法 | 正确方案 |
---|---|---|
分页查询 | limit 1000000,10 | where id > last_id limit |
状态字段索引 | 建在gender列 | 用枚举值或放弃索引 |
json字段查询 | where json->'$.id'=10 | 生成列+索引 |
模糊查询 | like '%关键字%' | 全文索引或es |
// 分页优化java实现 public page<user> getusers(long lastid, int limit) { string sql = "select * from user where id > ? order by id asc limit ?"; return jdbctemplate.query(sql, new beanpropertyrowmapper<>(), lastid, limit); }
六、面试考点区
问题1:varchar字段传int参数为何索引失效?
答:触发隐式转换→索引列计算→b+树失效→全表扫描
问题2:如何判断索引选择性?
答:select count(distinct col)/count(*) from table
结果>0.2适合建索引
问题3:explain中哪些信号危险?
type: all
(核爆级)extra: using filesort
(排序灾难)rows: 1000000
(预估扫描行数)
七、终极总结:与索引和平共处原则
设计阶段
- 优先整数字段索引
- 联合索引遵循asc排序原则
开发阶段
// mybatis防类型事故 @param("userid") long userid // 而非integer
运维阶段
-- 每月执行 analyze table orders; optimize table critical_data;
最后忠告:索引不是银弹!200万数据以下,精心设计的索引比分布式更有效;500万以上,考虑分库分表+索引的组合拳。
附录:索引健康检查清单
- [ ] 所有sql都通过explain验证
- [ ] 联合索引列顺序符合查询模式
- [ ] 避免在where子句中使用函数
- [ ] 定期清理冗余索引(工具:pt-duplicate-key-checker)
- [ ] 为慢查询设置监控(>0.5秒报警)
到此这篇关于一文揭秘mysql索引失效原因与优化方案的文章就介绍到这了,更多相关mysql索引失效内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!