1
我有一个表,包含历史记录。只要计数得到更新,就会添加一条记录,指定当时取得新值。表格模式如下所示:Postgres查询调整
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
现在我希望获得过去七天内每天更新的记录总数。这是我想出的:
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.347ms)。 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万行。我能做些什么来提高此查询的性能?理想情况下,我希望它在一秒钟内运行,以便我可以将其缓存并每天在后台更新一次。
尝试在'created :: date'上创建一个索引,并在current_date - 7和current_date之间添加where子句'where created :: date。顺便说一句:将'created'转换为时间戳的目的是什么?它*已*是一个时间戳。 –
@a_horse_with_no_name有趣的我没有注意到我正在那样做。我将这个索引添加到'created :: date'和'WHERE'子句中来检查 –
在这里打我,并告诉我为什么'在project_accountrecord上创建索引(created :: date DESC);'returns'ERROR :“::”处或附近的语法错误。 –