如何在PostgreSQL中的外表SELECT MAX(id)查询中使用索引?

szi*_*mek 7 database postgresql foreign-data-wrapper

我有一个外表(使用postgresql_fdw外部数据包装器),我需要找到最大ID来复制所有记录.当我运行SELECT MAX(id) FROM foreign_table它似乎没有使用索引:

Aggregate  (cost=205.06..205.07 rows=1 width=4) (actual time=13999.535..13999.535 rows=1 loops=1)
  ->  Foreign Scan on foreign_table  (cost=100.00..197.75 rows=2925 width=4) (actual time=1.288..13632.768 rows=1849305 loops=1)
Planning time: 0.087 ms
Execution time: 14019.179 ms
Run Code Online (Sandbox Code Playgroud)

当我SELECT MAX(id) FROM table在"真实"表上运行相同的query()时,它使用索引:

Result  (cost=0.45..0.46 rows=1 width=0) (actual time=0.164..0.165 rows=1 loops=1)
  InitPlan 1 (returns $0)
    ->  Limit  (cost=0.43..0.45 rows=1 width=4) (actual time=0.152..0.153 rows=1 loops=1)
       ->  Index Only Scan Backward using table_pkey on table  (cost=0.43..46102.55 rows=1821907 width=4) (actual time=0.143..0.143 rows=1 loops=1)
             Index Cond: (id IS NOT NULL)
             Heap Fetches: 1
Total runtime: 0.270 ms
Run Code Online (Sandbox Code Playgroud)

具有外表的数据库具有版本9.4.4,具有"真实"表的数据库具有版本9.3.9.

有没有办法在第一个查询中使用索引?

kli*_*lin 10

Postgres_fdw无法访问索引.使用远程服务器上的视图,例如:

create view test_max as
select max(val) max_val
from test;
Run Code Online (Sandbox Code Playgroud)

在本地服务器上定义远程视图的包装器:

create foreign table back_test_max (
    max_val int
)
    server back_server
    options (schema_name 'public', table_name 'test_max');
Run Code Online (Sandbox Code Playgroud)

选择on back_test_max将使用远程视图,因此也使用原始远程表的索引.

  • 如果您的应用程序同时广泛使用两个数据库,则值得考虑使用两个连接.在许多情况下,此解决方案将更有效.Fdw是一个相对较新的功能,可能会在未来开发. (2认同)