gpt4 book ai didi

postgresql - 使用 Limit 和 HashAggregates 的慢查询

转载 作者:行者123 更新时间:2023-11-29 13:32:34 25 4
gpt4 key购买 nike

Postgres 9.3

在下面的示例查询中,为什么 HashAggregate 处理 1000 万行(在 5 秒内)而不是在收集到限制指定的 1 行后立即停止(应该少于 1 毫秒)?

我有很多有限查询的问题...HashAggregate 使有限查询花费只要 无限查询...这使得限制完全无用。

有没有收集到n行就停不下来的原因?

创建一些测试数据:

create table foo (x integer);
insert into foo (x) (select * from generate_series(1, 10000000));

运行查询:

explain analyze
select x from foo group by x limit 1;

或使用 distinct 而不是 group by(产生相同的查询计划!):

explain analyze
select distinct x from foo limit 1;

http://explain.depesz.com/s/arPX

 Limit  (cost=176992.00..176992.01 rows=1 width=4) (actual time=5185.125..5185.125 rows=1 loops=1)
-> HashAggregate (cost=176992.00..176994.00 rows=200 width=4) (actual time=5185.124..5185.124 rows=1 loops=1)
-> Seq Scan on foo (cost=0.00..150443.20 rows=10619520 width=4) (actual time=0.018..949.926 rows=10000000 loops=1)
Total runtime: 5244.966 ms

最佳答案

在具有“order by”、“distinct”或聚合函数的查询中,必须先收集、排序和聚合整个查询结果,然后才能应用限制(无论限制数是多少)。您可以通过多种方式重写查询以获得相同的结果,但速度更快,但是,我需要看到更逼真的查询,因为该示例对于实际用例来说并不是很现实。

在考虑您的示例时,请考虑数据库如何确定要显示的结果(限制 1).. 它必须执行某种排序。我假设您的实际示例将包含一个 > 1 的限制,但我使用的是限制 1,那么有很多方法可以重写查询以利用它们的有限行。

关于postgresql - 使用 Limit 和 HashAggregates 的慢查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20128831/

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