sql - 按查询索引 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 行的表进行表扫描
解决方案
对于此查询:
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 by
distinct on
推荐阅读
- sql-server - 使用 SQL Server 脚本远程移动文件
- delphi - Delphi通过子字符串搜索比较2个字符串列表并将匹配项合并到另一个字符串列表中
- ios - 访问通话期间出现的 AlertController
- angular - 在 Angular 2+ 中使用 Observables 时发生的错误
- spring-boot - Spring Boot中的分页带有表单参数
- python - 在 Hy 中指定元类的语法
- javascript - 单击单选按钮时如何激活下拉列表
- .htaccess - 如何在不同端口上的 codeigniter 中删除 index.php
- java - Spring WebSocket StompHeaderAccessor
- branch - 在 Fossil 中更新分支