问题描述
我们在 AWS RDS 中托管了多个 postgresql 数据库,我想知道是否可以将它们连接在一起并对多个数据库运行查询,例如:
SELECT * FROM databaseA.TableX ax
LEFT JOIN databaseB.TableX bx ON bx.id = ax.id
我记得 sql Server 有这个功能,它叫做链接服务器。
解决方法
这是完整的命令序列:
-- Install extension
CREATE EXTENSION IF NOT EXISTS postgres_fdw WITH SCHEMA "public";
-- Link the foreign server
CREATE SERVER foreign_server
FOREIGN DATA WRAPPER postgres_fdw
OPTIONS (host '<url>',port '5432',dbname '<database>');
-- Map the local user with the foreign one
CREATE USER MAPPING FOR <local user>
SERVER foreign_server
OPTIONS (user '<foreign user>',password '<foreign user password>');
-- Create locally a schema
CREATE SCHEMA IF NOT EXISTS "northwind";
-- Import the foreign schema into the new local one
IMPORT FOREIGN SCHEMA "public" FROM SERVER foreign_server INTO "northwind";
-- Select from foreign table
SELECT * FROM "northwind"."categories";