首页 > 解决方案 > 使用子查询作为谓词时如何获得准确的行估计

问题描述

我在 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)

标签: sqlpostgresqloptimizationquery-optimization

解决方案


推荐阅读