【发布时间】:2014-12-18 20:15:53
【问题描述】:
我正在执行大量的 sql 选择,如下所示。想象一下,我们有一个包含航班的数据库,其中每个航班当然可能有出境和入境机场、出发日期、始发地和目的地之间的停靠点数(长途航班),当然还有价格。
我现在想选择一条特定路线,并选择停靠次数最少的路线,当然还有其中最优惠的路线。
CREATE TABLE flights(
id integer
outbound character varying,
inbound character varying,
date timestamp,
stops integer
price numeric
);
CREATE INDEX my_idx ON flights (outbound, inbound, date, stops, price);
select * from flights where outbound = 'SFO' and inbound = 'SYD' and date = '2015-10-10' and stops < 2 order by stops asc, price asc.
问题:使用explain-analyze 的成本相当高:
Sort (cost=9.78..9.79 rows=1 width=129) (actual time=0.055..0.055 rows=4 loops=1)
Sort Key: stops, price
Sort Method: quicksort Memory: 26kB
-> Index Scan using my_idx (cost=0.42..9.77 rows=1 width=129) (actual time=0.039..0.041 rows=4 loops=1)
Index Cond: ((date = '2015-10-10'::date) AND ((outbound)::text = 'SFO'::text) AND (stops < 2) AND ((inbound)::text = 'SYD'::text))
Total runtime: 0.079 ms
如果我只是按价格排序而没有停止,那么成本是可以的(0.42)。但是按站点排序会以某种方式增加成本。
如何降低成本?
postgresql 9.3.2
【问题讨论】:
-
您的 Postgres 版本至关重要(并且应该始终在问题中)。
-
postgresql 9.3.2以上更新 -
Err... 估计成本实际上很小。
0.42..9.77->9.78..9.79。那里的成本很高的是定位行。你确定你应该担心排序四行的成本吗? :-) -
您真的需要 all 列 (
SELECT *) 还是可以减少该列? -
我不知道,但我认为分拣成本相当高,也许我可以以某种方式降低它们。
标签: sql database postgresql