gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:46:58 24 4
gpt4 key购买 nike

我有一个外部表(使用 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

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

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

带有外部表的数据库版本为 9.4.4,带有“真实”表的数据库版本为 9.3.9。

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

最佳答案

Postgres_fdw 无法访问索引。在远程服务器上使用 View ,例如:

create view test_max as
select max(val) max_val
from test;

在本地服务器上为远程 View 定义一个包装器:

create foreign table back_test_max (
max_val int
)
server back_server
options (schema_name 'public', table_name 'test_max');

选择 back_test_max 将使用远程 View ,因此也使用原始远程表的索引。

关于database - 如何在 PostgreSQL 的外表 SELECT MAX(id) 查询中使用索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33872467/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com