每日一Go·MySQL-16、索引设计实战案例拆解

本文深入剖析MySQL索引设计的核心原则与工业级方法论,涵盖联合索引顺序、覆盖索引、游标分页优化、OLTP/OLAP分离等关键技术。通过4个典型线上案例(订单查询、深分页、统计分析、group by排序),揭示90%索引失效的根本原因,并给出可落地的五步法、口诀及避坑指南,强调基于EXPLAIN反向推导最优访问路径的工程思维。

真正拉开差距的不是“会建索引”,而是“会设计索引”. 核心认知:建索引 ≠ 会索引 索引设计是一门工程艺术

一、为什么 90% 的索引设计都是错的?

常见错误:

1. 有查询就加索引
2. 一个字段一个索引
3. 看字段就决定顺序
4. 只看 where,不看 order by
5. 不考虑回表 & 覆盖索引

最终结果:索引一堆,SQL 还是慢

二、索引设计核心 5 大原则

1. 以 SQL 为中心,而不是以字段为中心
2. 以访问路径为导向,而不是以业务直觉为导向
3. 优先联合索引,避免单列索引堆积
4. 最大化覆盖索引,最小化回表
5. 索引数量 ≤ 5,宁缺毋滥

三、索引设计四步法(工业级)

1. 统计核心 SQL
2. 提取 where + order by + group by
3. 设计联合索引
4. 用 explain 反推验证

四、实战案例 1:订单列表查询优化

SELECT *
FROM orders
WHERE user_id = ?
  AND status = ?
ORDER BY create_time DESC
LIMIT 20;

错误索引设计

idx_user
idx_status
idx_create_time

explain 结果

type: ref
key: idx_user
rows: 50000
extra: Using where; Using filesort

问题:

正确索引设计

索引顺序分析:

字段类型
user_id等值
status等值
create_time排序

联合索引:

index(user_id, status, create_time desc)

优化效果

指标优化前优化后
扫描行数5 万20
排序filesortindex
耗时380ms4ms

性能提升 95 倍

五、实战案例 2:后台搜索分页(深分页)

SELECT *
FROM orders
WHERE status = 1
ORDER BY id DESC
LIMIT 100000,20;

索引设计

index(status, id desc)

但依然慢:索引只能解决排序,解决不了 offset 扫描

终极设计(游标分页 + 覆盖索引)

SELECT id, amount, status
FROM orders
WHERE status = 1
  AND id < ?
ORDER BY id DESC
LIMIT 20;
index(status, id desc, amount)

特点:不回表、不扫描历史数据、毫秒级响应

六、实战案例 3:统计分析类 SQL

SELECT count(*)
FROM orders
WHERE user_id = ?
  AND create_time >= ?
  AND create_time < ?;

错误索引

index(user_id)
index(create_time)

正确索引设计

index(user_id, create_time)

七、实战案例 4:group by + 排序综合优化

SELECT user_id, count(*)
FROM orders
WHERE status = 1
GROUP BY user_id
ORDER BY count(*) DESC
LIMIT 20;

常规索引

index(status, user_id)

group by 仍需临时表 + filesort

架构级优化方案

建立统计表 + 定时聚合
orders → order_stat_day → API 查询

核心思想:OLTP 和 OLAP 分离

八、索引顺序设计口诀

等值在前,范围在后;排序紧跟,分页再后;覆盖结尾,回表减少。

where a=? and b=? and c>?
order by d
select e

最优索引:

(a, b, c, d, e)

九、索引设计 5 大经典坑

  1. 单列索引陷阱
a, b, c 各一个索引 ❌
(a,b,c) 一个联合索引 ✅
  1. 范围字段放前
(create_time, user_id) ❌
(user_id, create_time) ✅
  1. select * 毁掉覆盖索引
select * ❌
select id,xx,xx ✅
  1. 过度索引
索引 > 6 → 写入性能直线下降
  1. 从不 explain
不 explain 的索引设计 = 盲人摸象

十、真实线上索引优化案例

表:订单流水表 3000 万数据

原索引:

idx_user
idx_status
idx_time

慢 SQL:

select * from orders
where user_id=? and status=?
order by create_time desc
limit 20;

优化索引

index(user_id, status, create_time desc, id, amount)

SQL改写:

select id, amount
from orders
where user_id=? and status=?
order by create_time desc
limit 20;

优化效果

指标优化前优化后
扫描30万20
耗时1.2s5ms

十一、索引设计通用模板

遇到 SQL,直接套:

1. 过滤条件(where)
2. 排序字段(order by)
3. 分组字段(group by)
4. 返回字段(select)

十二、总结

索引设计不是背规则,而是通过 SQL 反向推导最短访问路径。


源码地址

???

如果您喜欢这篇文章,请您(点赞、分享、亮爱心),万分感谢!

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址