sql - 使用子查询作为谓词时如何获得准确的行估计
问题描述
我在 PostgreSQL(13.2) 中有这个问题,当使用子查询作为谓词时它无法获得准确的行估计(它使用 0.33333 作为默认选择性)。如何为 Q1 的良好查询计划获得准确的行估计?
我可以将 Q1(一个查询)拆分为首先获取值的 Q2(两个查询),然后使用第二次往返来查询 DB,但我想知道这是唯一的方法。如何避免第二次往返?
create table t (
id serial primary key,
value int
);
insert into t (value) select generate_series(1, 1000000);
create index t_value on t(value);
analyze t;
-- Q1, estimate rows=333333
explain select * from t where value < (select value from t where id=1000000);
Index Scan using t_value on t (cost=3.07..8317.99 rows=333333 width=8)
Index Cond: (value < $0)
InitPlan 1 (returns $0)
-> Index Scan using t_pkey on t t_1 (cost=0.42..2.64 rows=1 width=4)
Index Cond: (id = 1000000)
-- Q2 estimate rows=999999
select value from t where id=1000000; -- 1000000
explain select * from t where value < 1000000;
Seq Scan on t (cost=0.00..16925.00 rows=999999 width=8)
Filter: (value < 1000000)
解决方案
推荐阅读
- python - Sqlalchemy 只选择一列(语法> 1.4!)
- python - How to read file chunk by chunk?
- r - 我可以使用 R {targets} 包为不同的目标设置不同的并行度吗?
- html - 如何制作响应式图像?
- python-3.x - 如何在 Django Rest Framework 中使用 base64 上传多个文件?
- php - 如何将 AES 解密从 Javascript 转换为 php
- php - Elementor Pro 类 - 找不到类
- python - Pygame set_mode 没有显示正确的大小
- javascript - 为什么 beforeDestroyed 函数不起作用?
- javascript - 如何在计算的表单字段中使用 wordpress 帖子标题?