如何为此查询创建索引?我已经尝试过可以想到的每种可能的索引组合,但解释计划总是显示正在使用SEQ_SCAN。
select exchange_id, currency, max(timestamp) timestamp2
from exchange_balance
where account_id = 'foo'
group by exchange_id, currency
该表现在不大,因此实际上速度很快,但是会很快增长。
PostgreSQL 9.6
[edit]按col添加了一个群组-抱歉
我已经尝试过例如:
CREATE INDEX idx_exchange_balance_1 ON exchange_balance (exchange_id, currency, timestamp desc, account_id);
但是总是对具有4.5万行的表进行表扫描
答案 0 :(得分:1)
对于此查询:
select exchange_id, currency, max(timestamp) as timestamp2
from exchange_balance
where account_id = 'foo'
group by exchange_id, currency;
最好的索引是(account_id, exchange_id, currency, timestamp desc)
。
在Postgres中,使用以下命令可能会更有效:
select distinct on (account_id, exchange_id, currency) exchange_id, currency, timestamp
from exchange_balance
where account_id = 'foo'
order by account_id, exchange_id, currency, timestamp desc;
严格来说,account_id
或order by
子句中不需要distinct on
。但是保留它们可以使查询推广到多个帐户。