简单查看postgresql查询的算法改进

Gre*_*ind 5 sql algorithm postgresql complexity-theory

高级:我能做到这一点order by,group by基于sum 任何更快吗?(PG 8.4,fwiw.,在非小桌子上......想想O(数百万行))

假设我有一个这样的表:

                                 Table "public.summary"
   Column    |       Type        |                      Modifiers
-------------+-------------------+------------------------------------------------------
 ts          | integer           | not null default nextval('summary_ts_seq'::regclass)
 field1      | character varying | not null
 otherfield  | character varying | not null
 country     | character varying | not null
 lookups     | integer           | not null


Indexes:
    "summary_pk" PRIMARY KEY, btree (ts, field1, otherfield, country)
    "ix_summary_country" btree (country)
    "ix_summary_field1" btree (field1)
    "ix_summary_otherfield" btree (otherfield)
    "ix_summary_ts" btree (ts)
Run Code Online (Sandbox Code Playgroud)

我想要的查询是:

select summary.field1,
    summary.country,
    summary.ts,
    sum(summary.lookups) as lookups,
from summary
where summary.country = 'za' and
    summary.ts = 1275177600
group by summary.field1, summary.country, summary.ts
order by summary.ts, lookups desc, summary.field1
limit 100;
Run Code Online (Sandbox Code Playgroud)

(英语:在特定(ts,国家)的前100个字段1,其中'topness'是任何匹配行的查找总和,无论其他字段的值如何)

是否有什么我能做的,只能加快这?从算法来看,这似乎是一种全表扫描的东西,但我可能会遗漏一些东西.

小智 1

为了能够提出任何建议,您应该发布查询的执行计划。

“OMG Ponies”是对的:limit 100 会将整体结果限制为 100 行,它不适用于个别组!

Postgres Wiki 中有一篇很好的文章,解释了如何发布与慢速查询相关的问题:

http://wiki.postgresql.org/wiki/SlowQueryQuestions