【问题标题】:PostgreSQL not using index-only scanPostgreSQL 不使用仅索引扫描
【发布时间】:2020-09-06 06:19:36
【问题描述】:

我正在使用 Postgres 12。我有一个包含 999900 行的 sales_history 表。表中的列包括:

order_id numeric NOT NULL,
product_id numeric NOT NULL,
customer_id numeric NOT NULL,
sales_person_id numeric,
quantity numeric NOT NULL,
unit_price numeric,
sale_amount numeric,
sales_date date,
total_amount numeric,
CONSTRAINT sales_history_pkey PRIMARY KEY (order_id)

我的样本数据:

我有这个问题:

select sales_date
from sales_history
where (quantity * unit_price) between 5000000 and 10000000

我为 (quantity * unit_price) 和列 sales_date 创建了一个索引,我希望查询使用仅索引扫描

create index idx_sale_diff on sales_history( (quantity * unit_price), sales_date )

但是,查询改用位图扫描:

我尝试了 VACUUM 和 ANALYZE 但它仍然是位图扫描

有人能解释一下为什么这个查询没有使用 index-only scan 吗?据我了解,查询所需的所有列都在索引中可用,因此无需进行位图扫描

提前致谢:D

【问题讨论】:

    标签: postgresql indexing


    【解决方案1】:

    可能在表的可见性映射中没有足够的块标记为“全部可见”,因此PostgreSQL在很多情况下必须访问表来确定该行是否可见。

    解决办法是

    VACUUM sales_history;
    

    这将更新可见性地图。

    您必须定期VACUUM 一个表才能获得仅索引扫描。对于INSERT-only 表,在低于 v13 的 PostgreSQL 版本中不会自动发生这种情况。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-19
      • 1970-01-01
      • 2015-06-10
      • 1970-01-01
      • 2016-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多