连接来自不同数据库的表 (PostgreSQL)

Syl*_*NFF 2 sql postgresql join cross-database

是否可以使用 PostgreSQL 连接来自同一服务器中不同数据库的表?如果是这样,如何?

小智 8

假设您db1在 postgres 的数据库中。然后,

SELECT * FROM table1 tb1 
LEFT JOIN (SELECT * FROM dblink('dbname=db2','SELECT id, code FROM table2') 
AS tb2(id int, code text);) 
USING (code)
Run Code Online (Sandbox Code Playgroud)

将在所述列上加入 tb1 和 tb2(来自不同数据库的其他表)。在这个例子中,我曾经dblink这样做过。tb1tb2代表您的桌子。用您的表名和其他数据库名替换table1和。table2db2


Mab*_*sen 6

您可以使用dblinkforeign_table通过postgresql_fdw.

  1. 数据库链接
dblink 是一个支持从数据库会话中连接到其他 PostgreSQL 数据库的模块。

你可以在这里阅读文档。

  1. Foreign Table
The postgres_fdw module provides the foreign-data wrapper postgres_fdw, which can be used to access data stored in external PostgreSQL servers. The functionality provided by this module overlaps substantially with the functionality of the older dblink module. But postgres_fdw provides more transparent and standards-compliant syntax for accessing remote tables, and can give better performance in many cases.

You can read document here.