首页 > 解决方案 > PostgreSQL 慢的不同的地方

问题描述

想象一下下表:

CREATE TABLE drops(
    id BIGSERIAL PRIMARY KEY,
    loc VARCHAR(5) NOT NULL,
    tag INT NOT NULL
);

我想要做的是执行查询,我可以在其中找到值与标签匹配的所有唯一位置。

SELECT DISTINCT loc
FROM drops
WHERE tag = '1'
GROUP BY loc;

我不确定是因为它的大小(它的 9m 行大!)还是我效率低下,但是查询花费的时间太长,用户无法有效地使用它。在我写这篇文章的时候,上面的查询花了我 1:14 分钟。

我可以利用任何技巧或方法将其缩短到几秒钟吗?

非常感激!

执行计划:

"Unique  (cost=1967352.72..1967407.22 rows=41 width=4) (actual time=40890.768..40894.984 rows=30 loops=1)"
"  ->  Group  (cost=1967352.72..1967407.12 rows=41 width=4) (actual time=40890.767..40894.972 rows=30 loops=1)"
"        Group Key: loc"
"        ->  Gather Merge  (cost=1967352.72..1967406.92 rows=82 width=4) (actual time=40890.765..40895.031 rows=88 loops=1)"
"              Workers Planned: 2"
"              Workers Launched: 2"
"              ->  Group  (cost=1966352.70..1966397.43 rows=41 width=4) (actual time=40879.910..40883.362 rows=29 loops=3)"
"                    Group Key: loc"
"                    ->  Sort  (cost=1966352.70..1966375.06 rows=8946 width=4) (actual time=40879.907..40881.154 rows=19129 loops=3)"
"                          Sort Key: loc"
"                          Sort Method: quicksort  Memory: 1660kB"
"                          ->  Parallel Seq Scan on drops  (cost=0.00..1965765.53 rows=8946 width=4) (actual time=1.341..40858.553 rows=19129 loops=3)"
"                                Filter: (tag = 1)"
"                                Rows Removed by Filter: 3113338"
"Planning time: 0.146 ms"
"Execution time: 40895.280 ms"

该表在loc和上编制索引tag

标签: postgresqldistinctwhere

解决方案


您的 40 秒用于顺序读取整个表格,丢弃 3113338 行以仅保留 19129。

补救措施很简单:

CREATE INDEX ON drops(tag);

但是你说你已经这样做了,但我很难相信。你使用的命令是什么?

将查询中的条件从

WHERE tag = '1'

WHERE tag = 1

它恰好可以工作,因为'1'它是文字,但不要尝试比较字符串和数字。

并且,如前所述,保留DISTINCTGROUP BY,但不能同时保留。


推荐阅读