1
0
mirror of https://github.com/Snailclimb/JavaGuide synced 2025-06-16 18:10:13 +08:00

[docs update]添加深度分页问题的原因

This commit is contained in:
Guide 2024-10-11 11:23:42 +08:00
parent a43c620c60
commit 107337c8b7
2 changed files with 7 additions and 10 deletions

View File

@ -18,20 +18,18 @@ head:
# MySQL 在无法利用索引的情况下跳过1000000条记录后再获取10条记录 # MySQL 在无法利用索引的情况下跳过1000000条记录后再获取10条记录
SELECT * FROM t_order ORDER BY id LIMIT 1000000, 10 SELECT * FROM t_order ORDER BY id LIMIT 1000000, 10
``` ```
## 深度分页问题的原因 ## 深度分页问题的原因
**全表扫描**当OFFSET值较大时MySQL可能会选择执行全表扫描而不是使用索引。
![image](https://github.com/user-attachments/assets/d2537428-74db-4eba-bd1b-20b0ef681b8e)
![image](https://github.com/user-attachments/assets/00467d02-b5bd-4241-8145-acded334b76a)
具体的临界点每个机器不一样我的机器上是5980为什么产生呢 当查询偏移量过大时MySQL 的查询优化器可能会选择全表扫描而不是利用索引来优化查询。这是因为扫描索引和跳过大量记录可能比直接全表扫描更耗费资源。
![image](https://github.com/user-attachments/assets/19bb5403-398b-4bff-934a-7db2e31995aa)
![image](https://github.com/user-attachments/assets/d01a5b84-a47e-4ddd-966d-520cc3d3b3bd)
MySQL数据库的查询优化器是采用了基于代价的而查询代价的估算是基于CPU代价和IO代价。
如果MySQL在查询代价估算中认为全表扫描方式比走索引扫描的方式效率更高的话就会放弃索引直接全表扫描。
这就是为什么在大分页的SQL查询中明明给该字段加了索引但是MySQL却走了全表扫描的原因。
![深度分页问题](https://oss.javaguide.cn/github/javaguide/mysql/deep-pagination-phenomenon.png)
不同机器上这个查询偏移量过大的临界点可能不同,取决于多个因素,包括硬件配置(如 CPU 性能、磁盘速度)、表的大小、索引的类型和统计信息等。
![转全表扫描的临界点](https://oss.javaguide.cn/github/javaguide/mysql/deep-pagination-phenomenon-critical-point.png)
MySQL 的查询优化器采用基于成本的策略来选择最优的查询执行计划。它会根据 CPU 和 I/O 的成本来决定是否使用索引扫描或全表扫描。如果优化器认为全表扫描的成本更低它就会放弃使用索引。不过即使偏移量很大如果查询中使用了覆盖索引covering indexMySQL 仍然可能会使用索引,避免回表操作。
## 深度分页优化建议 ## 深度分页优化建议

View File

@ -346,7 +346,6 @@ Spring 框架中用到了哪些设计模式?
- 《Spring 技术内幕》 - 《Spring 技术内幕》
- <https://blog.eduonix.com/java-programming-2/learn-design-patterns-used-spring-framework/> - <https://blog.eduonix.com/java-programming-2/learn-design-patterns-used-spring-framework/>
- <http://blog.yeamin.top/2018/03/27/单例模式-Spring%20单例实现原理分析/>
- <https://www.tutorialsteacher.com/ioc/inversion-of-control> - <https://www.tutorialsteacher.com/ioc/inversion-of-control>
- <https://design-patterns.readthedocs.io/zh_CN/latest/behavioral_patterns/observer.html> - <https://design-patterns.readthedocs.io/zh_CN/latest/behavioral_patterns/observer.html>
- <https://juejin.im/post/5a8eb261f265da4e9e307230> - <https://juejin.im/post/5a8eb261f265da4e9e307230>