【发布时间】:2010-05-25 12:08:32
【问题描述】:
嗨
我有一个表格,其中包含文件及其类型,例如
CREATE TABLE files (
id SERIAL PRIMARY KEY,
name VARCHAR(255),
filetype VARCHAR(255),
...
);
和另一个用于保存文件属性的表,例如
CREATE TABLE properties (
id SERIAL PRIMARY KEY,
file_id INTEGER CONSTRAINT fk_files REFERENCES files(id),
size INTEGER,
... // other property fields
);
file_id 字段有一个索引。
文件表大约有 80 万行,属性表大约有 20 万行(并非所有文件都必须具有/需要属性)。
我想做聚合查询,例如查找所有文件类型的平均大小和标准偏差。但它非常慢 - 后一个查询大约需要 70 秒。我知道它需要顺序扫描,但似乎还是太多了。 这是查询
SELECT f.filetype, avg(size), stddev(size) FROM files as f, properties as pr
WHERE f.id = pr.file_id GROUP BY f.filetype;
还有解释
HashAggregate (cost=140292.20..140293.94 rows=116 width=13) (actual time=74013.621..74013.954 rows=110 loops=1)
-> Hash Join (cost=6780.19..138945.47 rows=179564 width=13) (actual time=1520.104..73156.531 rows=179499 loops=1)
Hash Cond: (f.id = pr.file_id)
-> Seq Scan on files f (cost=0.00..108365.41 rows=1140941 width=9) (actual time=0.998..62569.628 rows=805270 loops=1)
-> Hash (cost=3658.64..3658.64 rows=179564 width=12) (actual time=1131.053..1131.053 rows=179499 loops=1)
-> Seq Scan on properties pr (cost=0.00..3658.64 rows=179564 width=12) (actual time=0.753..557.171 rows=179574 loops=1)
Total runtime: 74014.520 ms
任何想法为什么它这么慢/如何使它更快?
【问题讨论】:
标签: sql postgresql aggregate