gpt4 book ai didi

sql - 为什么 Postgres 不将索引与 Distinct 一起使用?

转载 作者:行者123 更新时间:2023-11-29 12:03:55 31 4
gpt4 key购买 nike

我有这张表:

CREATE TABLE public.prodhistory (
curve_id int4 NOT NULL,
start_prod_date date NOT NULL,
prod_date date NOT NULL,
monthly_prod_rate float4 NOT NULL,
eff_date timestamp NOT NULL,
/* Keys */
CONSTRAINT prodhistorypk
PRIMARY KEY (curve_id, prod_date, start_prod_date, eff_date),
/* Foreign keys */
CONSTRAINT prodhistory2typecurves_fk
FOREIGN KEY (curve_id)
REFERENCES public.typecurves(curve_id)
) WITH (
OIDS = FALSE
);

CREATE INDEX prodhistory_idx_curve_id01
ON public.prodhistory
(curve_id);

约 4200 万行。

然后我执行这个查询:

SELECT DISTINCT curve_id FROM prodhistory

鉴于索引,我预计这会非常快。但不,270 秒。所以我解释,然后我得到:

HashAggregate  (cost=824870.03..824873.08 rows=305 width=4) (actual time=211834.018..211834.097 rows=315 loops=1)   
Output: curve_id
Group Key: prodhistory.curve_id
-> Seq Scan on public.prodhistory (cost=0.00..718003.22 rows=42746722 width=4) (actual time=12.751..200826.299 rows=43218808 loops=1)
Output: curve_id
Planning time: 0.115 ms
Execution time: 211848.137 ms

我没有阅读这些计划的经验,但数据库上的序列扫描似乎很糟糕。

有什么想法吗?我有点难过。

最佳答案

选择这个方案是因为 PostgreSQL 认为它更便宜。

可以通过设置进行比较

SET enable_seqscan=off;

然后重新运行您的EXPLAIN (ANALYZE) 语句。比较两种情况下的成本实际时间,并检查PostgreSQL估计是否正确。

如果您发现使用 Index ScanIndex Only Scan 实际上更便宜,您可以考虑调整成本参数以更好地匹配您的机器,例如降低 random_page_costcpu_index_tuple_cost 或提高 cpu_tuple_cost

关于sql - 为什么 Postgres 不将索引与 Distinct 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38208754/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com