postgres_fdw模塊
PostgreSQL 9.3 add postgres_fdw extension for accessing remote tables
PostgreSQL 9.3新增了一個postgres_fdw模塊, 已經(jīng)整合在源碼包中. 用于創(chuàng)建postgres外部表.
注:db_des為目標庫,developer_month_orders_data為表名。意思就是從查詢庫a中建立同名FOREIGN關(guān)聯(lián)表,
可以查詢目標庫中的數(shù)據(jù)。以下命令在需要建立的關(guān)聯(lián)庫中執(zhí)行。
目標庫中的表必須存在,也就是先建立好,否則從a庫,查詢會報找不到表錯誤
阿里云RDS,數(shù)據(jù)庫:PostgreSQL 9.4,跨實例數(shù)據(jù)庫不支持postgres_fdw建立外部表,坑?。?/p>
阿里云技術(shù)回復(fù)RDS需要10.0版本的 postgresql才支持跨實例。不然只能同一個實例下的不同數(shù)據(jù)庫之間的外部表。
-- 安裝 postgres_fdw 插件
CREATE EXTENSION postgres_fdw;
-- 創(chuàng)建遠程服務(wù)
CREATE SERVER remote_server FOREIGN DATA WRAPPER postgres_fdw;
-- 查看遠程服務(wù)
select * from pg_foreign_server ;
-- 修改遠程服務(wù)
alter server remote_server options (add hostaddr '11.216.10.215',
add port '5432', add dbname 'db_des');
-- SERVER賦權(quán)
grant usage on foreign server remote_server to postgres;
-- 在本地數(shù)據(jù)庫中創(chuàng)建user mapping
CREATE USER MAPPING FOR postgres server remote_server options (user 'postgres', password 'xxxxx');
-- 同樣創(chuàng)建枚舉
CREATE TYPE db_enum AS ENUM ('postgres', 'sqlserver', 'mysql');
-- 查看枚舉類型的oid
select oid from pg_type where typname='db_enum';
-- 創(chuàng)建外部表developer_month_orders_data
CREATE FOREIGN TABLE developer_month_orders_data(
id integer not null,
developer_user_id integer,
package_id integer,
order_month date,
create_datetime timestamp
) SERVER remote_server options (schema_name 'public',table_name 'developer_month_orders_data');
-- 查看外部表
select * from developer_month_orders_data;
ddl維護操作:
drop user mapping for postgres server server_remote ;
drop server server_remote;
drop extension postgres_fdw ;
drop foreign table test1;
補充:postgresql postgres_fdw 跨庫查詢
1 安裝擴展
create extension postgres_fdw;
2 本地創(chuàng)建server并查看 該server作用是在本地配置一個連接遠程的信息,下面的配置是要連接到遠程DB名稱是postgres數(shù)據(jù)庫
create server server_remote_rudy_01 foreign data wrapper postgres_fdw options(host ‘192.168.11.44',port ‘5432',dbname ‘vsphere_info');
查詢:
select * from pg_foreign_server ;**
3 創(chuàng)建用戶匹配信息并查看,在本地
for后面的postgres是本地登錄執(zhí)行的用戶名,option里存儲的是遠程的用戶密碼
create user mapping for postgres server server_remote_rudy_01 options(user ‘vsphere',password ‘viadmin');
4 本地創(chuàng)建外部表,指定server
CREATE FOREIGN TABLE v1_cost(sample_time TIMESTAMP,datacenter_id int4,host_id int4 ,cost NUMERIC) server server_remote_rudy_01 options (schema_name ‘public',table_name ‘vi_cost');
5 –導(dǎo)入指定的表,也可以不導(dǎo)入指定的表,也可以導(dǎo)入整個schema下面的表(可有可無的一步)
IMPORT FOREIGN SCHEMA public FROM SERVER server_remote_rudy_01 INTO public;
IMPORT FOREIGN SCHEMA public limit to(t1) FROM SERVER server_remote_rudy_01 INTO public;
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
您可能感興趣的文章:- PostgreSQL中使用dblink實現(xiàn)跨庫查詢的方法
- PostgreSQL數(shù)據(jù)庫中跨庫訪問解決方案
- PostgreSQL 流復(fù)制異步轉(zhuǎn)同步的操作
- PostgreSQL中Slony-I同步復(fù)制部署教程