如何为此查询创建索引?我已经尝试了所有可能的索引组合,但explain plan总是显示正在使用SEQ_扫描。
select exchange_id, currency, max(timestamp) timestamp2
from exchange_balance
where account_id = 'foo'
group by exchange_id, currency
这张桌子现在不大,所以它实际上很快,但它会很快长大。
PostgreSQL 9.6版
[编辑]按列添加了组-抱歉
我试过这个例如:
CREATE INDEX idx_exchange_balance_1 ON exchange_balance (exchange_id, currency, timestamp desc, account_id);
但是总是在一个有45k行的表上扫描一个表
最佳答案
对于此查询:
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
子句中不需要。但是保留它们允许查询扩展到多个帐户。关于sql - 通过查询索引最大+组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56305982/