1

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

    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.347ms)。解释分析给出:

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 万行。我可以做些什么来提高这个查询的性能?理想情况下,我希望它在一秒钟内运行,这样我就可以缓存它并每天在后台更新几次。

4

1 回答 1

2

Now, your query must scan whole table, calculate result and limit to 7 recent days. You can speedup query by scanning only last 7 days (or more if you don't update records every day):

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

Another aproach is to cache historical results in extra table and count only current day.

于 2013-10-01T10:27:51.397 回答