PostgreSQL慢速DISTINCT WHERE

问题描述 投票:1回答:2

想象一下下表:

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"

该表在loctag上编入索引。

postgresql distinct where
2个回答
1
投票

你的40秒是按顺序读取整个表格,扔掉3113338行只保留19129。

补救措施很简单:

CREATE INDEX ON drops(tag);

但是你说你已经做到了,但我觉得很难相信。你用的命令是什么?

更改查询中的条件

WHERE tag = '1'

WHERE tag = 1

它恰好起作用,因为'1'是一个文字,但不要试图比较字符串和数字。

并且,正如已经提到的,保持DISTINCTGROUP BY,但不是两者。


0
投票

如果您使用了GROUP BY子句,则无需使用DISTINCT关键字。省略这应该可以加快查询的运行时间。

© www.soinside.com 2019 - 2024. All rights reserved.