加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-13 18:06:03 所属栏目:百科 来源:网络整理
导读:高级:我可以根据总和进行分组 更快? (PG 8.4,fwiw.,在非小桌子上……想想O(数百万行)) 假设我有一个这样的表: Table "public.summary" Column | Type | Modifiers-------------+-------------------+---------------------------------------------------
高级:我可以根据总和进行分组
更快? (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)

我想要的查询是:

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.ts
order by summary.ts,lookups desc,summary.field1
limit 100;

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

我能做些什么来加速这个吗?在算法上
这似乎是一个全表扫描的东西,但我可能会遗漏一些东西.

此查询的任何查询计划都必须扫描与WHERE条件匹配的每一行,并按分组条件进行滚动 – 即,工作量与组的输入行数成比例,而不是结果行.

对于像这样的查询,最有效的查询计划是单个索引扫描.如果你按照这个顺序在(country,ts)上建立索引,这应该是可能的;使用该索引,此表单的每个可能查询都会解析为索引上的连续范围.但是,这仍然需要内存中的排序 – 可以使用不同的索引来避免这种情况.

正如其他人所说,发布执行计划是您的最佳选择.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读