# 查询优化

**查询优化**（Query optimization）是数据库管理系统为 SQL 查询选择执行计划的过程：它在逻辑等价的备选方案——例如连接顺序、连接算法和访问方法——中，选出预期运行最快或代价最低的一个。由于 SQL 是非过程化的，用户只说明想要什么数据，而不说明如何获取；优化器负责提供“如何”。基于代价的方法可追溯到 System R；这是 IBM 的实验性关系系统，其 1979 年由 P. 格里菲斯·塞林格（P. Griffiths Selinger）及其在 IBM 圣何塞（IBM San Jose）的同事发表的论文，描述了利用表统计信息以及 CPU 和磁盘利用率模型，为单表查询和连接查询选择访问路径。该架构包含三个组件——基数估计、代价模型和计划枚举——至今仍是大多数商业和开源优化器的基础<sup>[1](https://arxiv.org/abs/2101.01507)</sup>。

| 关键事实 | 详情 |
|---|---|
| 奠基性设计 | System R（塞林格、阿斯特拉汉（Astrahan）、钱伯林（Chamberlin）、洛里（Lorie）、普赖斯（Price），ACM SIGMOD 1979）利用统计信息和代价模型选择访问路径；其架构是后来优化器的基线 |
| 优化器输入 | 查询、数据库模式（表和索引定义）以及数据库统计信息<sup>[2](https://learn.microsoft.com/en-us/sql/relational-databases/performance/execution-plans?view=azuresqldb-current)</sup> |
| 三个组件 | 基数估计、代价模型和计划枚举（连接排序）；估计误差常常导致次优计划<sup>[1](https://arxiv.org/abs/2101.01507)</sup><sup> • </sup><sup>[3](https://link.springer.com/article/10.1007/s00778-021-00676-3)</sup> |
| 标准基准 | 连接顺序基准（Join Order Benchmark，JOB）：在具有相关性的真实 IMDB 数据集上运行的 113 条复杂多连接查询<sup>[4](https://ir.cwi.nl/pub/27562)</sup> |
| 估计器质量 | 所有经过测试的工业级基数估计器都会经常产生较大误差，尤其是对于跨连接的相关谓词<sup>[5](https://ir.cwi.nl/pub/24379)</sup> |
| 估计最不重要的时候 | 在 PostgreSQL 上运行 JOB 时，基数估计在无索引设置中影响很小（代价为真实基数基线的 1.01 至 1.68 倍），在高度并行的主内存执行中影响更小<sup>[6](https://arxiv.org/abs/2311.17293)</sup> |
| 学习型估计器 | 机器学习基数估计器可以改进计划，但广泛使用的 Q-Error 准确度指标并不能可靠预测端到端计划质量<sup>[7](https://arxiv.org/abs/2109.05877)</sup> |

## 基于代价的优化器如何工作

优化器接收查询、模式和统计信息，并构建一个或多个候选执行计划<sup>[2](https://learn.microsoft.com/en-us/sql/relational-databases/performance/execution-plans?view=azuresqldb-current)</sup>。对于每个计划，它估计两件事：基数，即流经每个算子的行数；以及代价，即计划将消耗的资源（CPU、I/O、内存）模型。然后它选择估计代价最低的计划<sup>[3](https://link.springer.com/article/10.1007/s00778-021-00676-3)</sup>。典型的计划选择包括连接算子的顺序、执行策略的选择（如哈希连接、排序连接或基于索引的连接）、谓词重排序，以及基于统计信息的分区裁剪<sup>[3](https://link.springer.com/article/10.1007/s00778-021-00676-3)</sup>。

基数信息通常来自直方图或样本等统计信息。包括 [PostgreSQL](https://www.edgepedia.org/zh/postgresql)、Oracle 和 Db2 在内的传统系统维护多种概要结构；SQL Server 主要根据随索引或统计信息创建的直方图推导估计值，而 MySQL 在通过 `ANALYZE TABLE` 管理的数据字典表中维护列直方图<sup>[6](https://arxiv.org/abs/2311.17293)</sup><sup> • </sup><sup>[8](https://learn.microsoft.com/en-us/sql/relational-databases/performance/intelligent-query-processing-cardinality-estimation-feedback?view=sql-server-ver17)</sup><sup> • </sup><sup>[9](https://dev.mysql.com/doc/refman/8.4/en/controlling-optimizer.html)</sup>。采样从随机数据样本估计基数，当数据规模或复杂性导致精确计算不可行时具有优势<sup>[10](https://faculty.ucmerced.edu/frusu/Papers/Report/2023-11-arxiv-ce-vs-noce.pdf)</sup>。PostgreSQL 通过 `default_statistics_target` 参数暴露统计信息粒度，其默认值为 100；更大的值会增加 `ANALYZE` 时间，但可能改善估计质量<sup>[11](https://www.postgresql.org/docs/current/runtime-config-query.html)</sup>。

计划枚举搜索语义等价的连接顺序空间，以最小化估计代价。由于可能计划的数量随表数量呈指数增长，优化器无法总是穷举枚举；当连接数量超过阈值时，PostgreSQL 会切换到遗传查询优化器<sup>[12](https://www.postgresql.org/files/documentation/pdf/9.6/postgresql-9.6-A4.pdf)</sup>。

## 基准证据说明了什么

连接顺序基准由慕尼黑工业大学的维克托·莱斯（Viktor Leis）及其在 CWI、TUM 和慕尼黑大学的同事在《查询优化器到底有多好？》（"How Good Are Query Optimizers, Really?"，VLDB 2015）中提出，并在 2018 年 VLDB Journal 论文中扩展；它在 IMDB 数据上运行 113 条多连接查询，该数据因其真实世界的相关性而被选中<sup>[4](https://ir.cwi.nl/pub/27562)</sup><sup> • </sup><sup>[5](https://ir.cwi.nl/pub/24379)</sup>。其发现塑造了该领域对优化器设计的理解：

- 所有经过测试的工业级基数估计器都会经常产生较大误差；采样解决了单表估计问题，但工业系统中没有任何技术能准确处理跨连接的相关谓词<sup>[4](https://ir.cwi.nl/pub/27562)</sup>。
- 估计对于找到良好的连接顺序至关重要，但如果引擎过于依赖估计，查询性能就会受损<sup>[5](https://ir.cwi.nl/pub/24379)</sup>。
- 代价模型对查询性能的影响远小于基数估计；在主内存环境中，即使极其简单的代价模型也能产生令人满意的结果<sup>[5](https://ir.cwi.nl/pub/24379)</sup>。
- 尽管基数估计次优，穷举动态规划枚举仍能改善性能<sup>[5](https://ir.cwi.nl/pub/24379)</sup>。

**基数估计并不总是决定性的。** 2023 年，[加州大学默塞德分校](https://www.edgepedia.org/zh/university-of-california-merced)（University of California, Merced）的阿索克·达塔（Asoke Datta）、布莱恩·灿（Brian Tsan）、叶斯道莱特·伊泽诺夫（Yesdaulet Izenov）和弗洛林·鲁苏（Florin Rusu）比较了在 PostgreSQL 上运行 JOB 时使用基数估计（CE）的优化器、不使用基数估计的优化器（no-CE，通过 Simpli-Squared 算法在没有任何统计信息的情况下对连接排序）以及真实基数基线（TrueCard）<sup>[6](https://arxiv.org/abs/2311.17293)</sup><sup> • </sup><sup>[13](https://arxiv.org/abs/2111.00163)</sup>。在仅能使用哈希连接的无索引设置中，CE 和 no-CE 计划的代价分别是 TrueCard 计划的 1.01 倍和 1.68 倍，运行时间分别是 1.07 倍和 1.28 倍，因此估计的影响很小<sup>[6](https://arxiv.org/abs/2311.17293)</sup>。在可用索引时，情况发生了变化：不准确的估计可能导致次优的物理算子，例如在本应使用索引扫描或嵌套循环连接时却使用了顺序扫描或哈希连接，即使连接顺序是最优的<sup>[6](https://arxiv.org/abs/2311.17293)</sup>。在一个最优 TrueCard 计划中，将某张表的扫描和连接算子替换后，代价增至原来的约八倍，运行时间增至原来的约 4.5 倍；对于另一张表，代价增至原来的约十一倍，运行时间增至原来的约 6.5 倍<sup>[10](https://faculty.ucmerced.edu/frusu/Papers/Report/2023-11-arxiv-ce-vs-noce.pdf)</sup>。同一研究发现，估计的影响在并行情况下会减弱：使用三个线程时，相对于单线程执行的加速比在整个工作负载上为 1.68 至 9.90，使用五个线程时达到 14.92，并且随着线程数增加，TrueCard 与其他方法之间的运行时间差距缩小；超过五个线程后，PostgreSQL 的进一步改善可以忽略不计<sup>[6](https://arxiv.org/abs/2311.17293)</sup><sup> • </sup><sup>[10](https://faculty.ucmerced.edu/frusu/Papers/Report/2023-11-arxiv-ce-vs-noce.pdf)</sup>。

## 学习型与自适应优化

机器学习已被应用于优化器的每个组件。学习型基数估计器从数据或查询工作负载预测结果规模，捕捉传统独立性假设遗漏的偏斜和相关谓词；乔少杰（Shao-Jie Qiao）及其同事的一项综述将这项工作分为监督和无监督方法，并指出四个活跃方向：基数和代价估计、基于学习的连接顺序选择、端到端学习型优化器以及文本到 SQL 模型<sup>[14](https://research.monash.edu/en/publications/learning-database-optimization-techniques-the-state-of-the-art-an/)</sup>。CAPE 等算子级深度网络将用于选择算子和连接算子的独立神经网络结合起来，以估计连接基数<sup>[15](https://www.sciencedirect.com/science/article/abs/pii/S0020025520309750)</sup>。

然而，部署会带来实际成本。韩宇星（Yuxing Han）及其同事的全面 CardEst 基准将十二种代表性估计器集成到 PostgreSQL 中，发现推理延迟很重要：一些数据驱动方法对每个子计划查询的推理时间接近一秒，这会损害短 OLTP 查询，即使执行更快；而对于长 OLAP 查询，计划质量比缓慢推理更重要<sup>[7](https://arxiv.org/abs/2109.05877)</sup>。同一研究表明，标准准确度指标 Q-Error 不能区分不同子计划估计的重要性，并提出了 P-Error，它能更好地跟踪端到端计划质量<sup>[7](https://arxiv.org/abs/2109.05877)</sup>。微软研究院（Microsoft Research）的李国镇（Kukjin Lee）、安舒曼·杜特（Anshuman Dutt）、维韦克·纳拉萨亚（Vivek Narasayya）和苏拉吉特·乔杜里（Surajit Chaudhuri）在 [Microsoft SQL Server](https://www.edgepedia.org/zh/microsoft-sql-server) 上进行的一项相关实证研究，将分析扩展到包含分组、聚合、外连接和子查询的复杂查询，并考察了位图过滤和自适应连接等技术能否减轻基数误差的影响<sup>[16](https://www.microsoft.com/en-us/research/publication/analyzing-the-impact-of-cardinality-estimation-on-execution-plans-in-microsoft-sql-server/)</sup>。

商业系统也在加入反馈回路。SQL Server 2022 引入了基数估计反馈：它检测估计行数与实际行数严重偏离的重复查询，测试另一种模型假设，并在能改善计划质量时将该修正作为查询存储（Query Store）提示持久化<sup>[8](https://learn.microsoft.com/en-us/sql/relational-databases/performance/intelligent-query-processing-cardinality-estimation-feedback?view=sql-server-ver17)</sup>。更广泛地说，自适应查询处理将一些优化决策移到执行时，利用运行时测量来修订计划<sup>[17](https://doi.org/10.1007/s00778-025-00936-6)</sup>。

## 实践轨迹

在成熟系统中，优化器质量一直在提高。宾夕法尼亚大学（University of Pennsylvania）助理教授瑞安·马库斯（Ryan Marcus）在 PostgreSQL 8 至 16 版本上运行 JOB，发现十年间尾部延迟大约减半，每个主要版本在基准上平均带来 15% 的改善，不过其中一部分收益来自执行引擎的变化，例如并行工作线程和 JIT 编译，而不仅仅是优化器<sup>[18](https://rmarcus.info/blog/2024/04/12/pg-over-time.html)</sup>。对实践者而言，基准证据转化为一种分工：当索引为优化器提供物理算子选择时，修正统计信息和估计最有帮助；而在仅扫描或高度并行的设置中，连接顺序占主导地位，甚至无统计信息的排序也能接近真实基数最优值<sup>[6](https://arxiv.org/abs/2311.17293)</sup>。

## References

1. [Z. Han et al. (2021). A Survey on Advancing the DBMS Query Optimizer: Cardinality Estimation, Cost Model, and Plan Enumeration. arXiv.](https://arxiv.org/abs/2101.01507)
2. [Execution Plan Overview, SQL Server documentation, Microsoft Learn.](https://learn.microsoft.com/en-us/sql/relational-databases/performance/execution-plans?view=azuresqldb-current)
3. [Data dependencies for query optimization: a survey. The VLDB Journal (2021).](https://link.springer.com/article/10.1007/s00778-021-00676-3)
4. [Query optimization through the looking glass, and what we found running the Join Order Benchmark. CWI repository (VLDB Journal 2018).](https://ir.cwi.nl/pub/27562)
5. [V. Leis et al. (2015). How Good Are Query Optimizers, Really? Proceedings of the VLDB Endowment 9(3), 204-215. CWI repository.](https://ir.cwi.nl/pub/24379)
6. [A. Datta, B. Tsan, Y. Izenov, F. Rusu (2023). Analyzing Query Optimizer Performance in the Presence and Absence of Cardinality Estimates. arXiv.](https://arxiv.org/abs/2311.17293)
7. [Y. Han et al. (2021). Cardinality Estimation in DBMS: A Comprehensive Benchmark Evaluation. arXiv / PVLDB 15(4).](https://arxiv.org/abs/2109.05877)
8. [Cardinality Estimation Feedback, SQL Server documentation, Microsoft Learn.](https://learn.microsoft.com/en-us/sql/relational-databases/performance/intelligent-query-processing-cardinality-estimation-feedback?view=sql-server-ver17)
9. [MySQL 8.4 Reference Manual: Controlling the Query Optimizer.](https://dev.mysql.com/doc/refman/8.4/en/controlling-optimizer.html)
10. [A. Datta et al. (2023). Query Optimization in the Presence and Absence of Cardinality Estimates (full report PDF), UC Merced.](https://faculty.ucmerced.edu/frusu/Papers/Report/2023-11-arxiv-ce-vs-noce.pdf)
11. [PostgreSQL Documentation: 19.7 Query Planning.](https://www.postgresql.org/docs/current/runtime-config-query.html)
12. [PostgreSQL 9.6 Documentation: Chapter 49, Overview of PostgreSQL Internals.](https://www.postgresql.org/files/documentation/pdf/9.6/postgresql-9.6-A4.pdf)
13. [Simpli-Squared: A Very Simple Yet Unexpectedly Powerful Join Ordering Algorithm Without Cardinality Estimates. arXiv.](https://arxiv.org/abs/2111.00163)
14. [S.-J. Qiao et al. (2025). Learning database optimization techniques: the state-of-the-art and prospects. Frontiers of Computer Science, Monash University repository.](https://research.monash.edu/en/publications/learning-database-optimization-techniques-the-state-of-the-art-an/)
15. [Join cardinality estimation by combining operator-level deep neural networks. Information Sciences 546 (2021).](https://www.sciencedirect.com/science/article/abs/pii/S0020025520309750)
16. [K. Lee, A. Dutt, V. Narasayya, S. Chaudhuri (2023). Analyzing the Impact of Cardinality Estimation on Execution Plans in Microsoft SQL Server. PVLDB 16(11), Microsoft Research.](https://www.microsoft.com/en-us/research/publication/analyzing-the-impact-of-cardinality-estimation-on-execution-plans-in-microsoft-sql-server/)
17. [Simple Adaptive Query Processing vs. Learned Query Optimizers: Observations and Analysis. The VLDB Journal 34, 62 (2025).](https://doi.org/10.1007/s00778-025-00936-6)
18. [R. Marcus (2024). Ten years of improvements in PostgreSQL's optimizer.](https://rmarcus.info/blog/2024/04/12/pg-over-time.html)

---
*Initially written Sep 17, 2026 · Reviewed: Sep 17, 2026; Sep 30, 2026; Oct 15, 2026 · Edited: Oct 15, 2026 · Last review: Oct 15, 2026*

Topic: 技术与人造世界 › 计算技术与数字系统 › 人工智能与数据 › Databases and data systems › SQL and query languages › Query processing and optimization concepts

Copyright 2026 Edgepedia

License: Edgepedia Community License 1.0, https://www.edgepedia.org/edgepedia/license

Source: https://www.edgepedia.org/zh/query-optimization

English original: https://www.edgepedia.org/query-optimization
