gpt4 book ai didi

sql - Postgres 查询调优

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

我有一个保存历史记录的表。每当更新计数时,都会添加一条记录,指定当时获取了一个新值。表架构如下所示:

    Column     |           Type           |                             Modifiers
---------------+--------------------------+--------------------------------------------------------------------
id | integer | not null default nextval('project_accountrecord_id_seq'::regclass)
user_id | integer | not null
created | timestamp with time zone | not null
service | character varying(200) | not null
metric | character varying(200) | not null
value | integer | not null

现在我想获取过去 7 天每天更新的记录总数。这是我想出的:

SELECT
created::timestamp::date as created_date,
count(created)
FROM
project_accountrecord
GROUP BY
created::timestamp::date
ORDER BY
created_date DESC
LIMIT 7;

这运行缓慢(11406.347 毫秒)。 EXPLAIN ANALYZE 给出:

Limit  (cost=440939.66..440939.70 rows=7 width=8) (actual time=24184.547..24370.715 rows=7 loops=1)
-> GroupAggregate (cost=440939.66..477990.56 rows=6711746 width=8) (actual time=24184.544..24370.699 rows=7 loops=1)
-> Sort (cost=440939.66..444340.97 rows=6802607 width=8) (actual time=24161.120..24276.205 rows=92413 loops=1)
Sort Key: (((created)::timestamp without time zone)::date)
Sort Method: external merge Disk: 146328kB
-> Seq Scan on project_accountrecord (cost=0.00..153671.43 rows=6802607 width=8) (actual time=0.017..10132.970 rows=6802607 loops=1)
Total runtime: 24420.988 ms

此表中有 680 万多行。我该怎么做才能提高此查询的性能?理想情况下,我希望它在一秒钟内运行,这样我就可以缓存它并每天在后台更新几次。

最佳答案

现在,您的查询必须扫描整个表,计算结果并限制为最近 7 天。您可以通过仅扫描最近 7 天(如果您不每天更新记录,则扫描更多)来加快查询速度:

where created_date>now()::date-'7 days'::interval

另一种方法是将历史结果缓存在额外的表中,只计算当天。

关于sql - Postgres 查询调优,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19113573/

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