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

Join tables from different databases (PostgreSQL)

是否可以使用 PostgreSQL 连接同一服务器上不同数据库的表?如果是,怎么做?

您可以使用 dblinkforeign_tablepostgresql_fdw

  1. dblink
dblink is a module that supports connections to other PostgreSQL databases from within a database session.

您可以阅读文档 here

  1. 国外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.

您可以阅读文档 here

假设您在 postgres 的数据库 db1 中。那么,

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

将在所述列上加入 tb1 和 tb2(来自不同数据库的其他 table)。在示例中,我使用 dblink 来执行此操作。 tb1tb2 代表您的 table。将 table1table2 替换为您的 table 名称,将 db2 替换为您的其他数据库名称。