sql慢查询优化

业务场景

线上订单列表分页查询,老写法:

sql 复制代码
select * from order 
where user_id=? and create_time between ? and ? 
order by create_time desc 
limit 10000,10

问题

• limit 偏移量太大,数据库要扫描前10000行再丢弃,极慢

• 只有单列索引,排序触发 Using filesort

• 接口响应3~5秒,频繁超时

优化方案

  1. 建联合索引

    idx_user_createtime (user_id, create_time, id)

  2. 改成游标分页(正确逻辑)

    第一页正常:

sql 复制代码
select id,xxx from order 
where user_id=? 
order by create_time desc,id desc 
limit 10

下一页带上一页最小时间+最小id,用 id < last_id

(因为是倒序:时间从新到旧、id从大到小)

sql 复制代码
select id,xxx from order 
where user_id=? 
and create_time < last_create_time 
and id < last_id
order by create_time desc,id desc 
limit 10

核心原理

倒序分页:desc 用 id < 上页最后一条id

正序分页:asc 用 id > 上页最后一条id

  1. 去掉 select *,只查必要字段

优化效果

SQL从3秒多降到10ms内,接口超时全部消失。

我给你一句面试口述原话,直接背:

当时线上订单列表用limit大偏移分页,越往后越慢,还触发了文件排序。我先建了user_id+create_time联合索引,然后把大偏移limit改成游标分页,倒序查询用id小于上一页最后一条id做翻页,避免数据库扫描大量无效数据,同时精简查询字段,优化后耗时从3秒多降到十几毫秒。

相关推荐
IT邦德2 小时前
OGG 26ai实时同步Oracle
数据库·oracle
Python大数据分析@2 小时前
有哪些好用又免费的SQL工具?
数据库·sql
哥本哈士奇2 小时前
SQL Server RAG 笔记1:图数据库构建
数据库
带鱼吃猫2 小时前
从原子性到串行化:数据库事务全解
数据库·mysql
网络工程小王2 小时前
[RAG 与文本向量化详解]RAG篇
数据库·人工智能·redis·机器学习
秋92 小时前
MySQL 8.4.9 LTS 与 MySQL 9.7.0 LTS 全方位深度对比
数据库·mysql
ffqws_2 小时前
Spring Boot 配置读取全解析:从 application.yml 到 Java 对象的完整链路
java·数据库·spring boot
HackTwoHub12 小时前
AI大模型网关存在SQL注入、附 POC 复现、影响版本LiteLLM 1.81.16~1.83.7(CVE-2026-42208)
数据库·人工智能·sql·网络安全·系统安全·网络攻击模型·安全架构
l1t12 小时前
DeepSeek总结的DuckLake构建基于 SQL 原生表格式的下一代数据湖仓
数据库·sql