首页 > 解决方案 > 按查询索引 max + group

问题描述

如何为此查询创建索引?我已经尝试了我能想到的所有可能的索引组合,但解释计划总是显示正在使用 SEQ_SCAN。

select exchange_id, currency, max(timestamp) timestamp2
    from exchange_balance
    where account_id = 'foo'
    group by exchange_id, currency

该表现在并不大,因此实际上很快,但它会快速增长。

PostgreSQL 9.6

[编辑] 按 col 添加了一个组 - 抱歉

例如,我已经尝试过:

CREATE INDEX idx_exchange_balance_1 ON exchange_balance (exchange_id, currency, timestamp desc, account_id);

但总是对有 45k 行的表进行表扫描

标签: sqlpostgresqlindexing

解决方案


对于此查询:

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;

严格来说,在or子句account_id中是不需要的。但是保留它们可以使查询泛化到多个帐户。order bydistinct on


推荐阅读