Postgres不同數據庫間訪問


Postgres中不同數據庫間無法直接訪問,比如有數據庫test1和test2,每個數據庫中都有一個表為tablea;我使用的操作系統為win8.1,postgres版本為9.3.6;使用pgAdminIII工具訪問postgres;

image

分別在兩個數據庫(test1,test2)中創建tablea;

test1數據庫創建tablea並插入數據:

create table tablea(id int,name varchar(10));

insert into tablea values

(1,’a’),(2,’b’);

test2數據庫創建tablea並插入數據:

create table tablea(id int,name varchar(10));

insert into tablea values

(1,’c’),(2,’d’);

從test1數據庫中分別訪問test1和test2數據庫中的表

image

image

所報的錯誤為:未實現數據庫關聯:”test2.public.tablea”  SQL 狀態:0A000

我上面寫表是按照:數據庫.模式.表名

SQL Server中模式是dbo,訪問的時候使用select * from test2.dbo.tablea;個人感覺pgAdminIII和SSMS類似,或者說各個數據庫窗口管理工具都類似,Mysql Workbench也類似。

現在先截個圖,看看test1數據可test2數據庫模式下面的函數個數(全部是0)

 image

在test1數據庫中打開SQL窗口,輸入create extension dblink;如下圖

image

再在test數據庫上刷新下,就會看到模式—public--函數,括號內數字不是0了

image

然后在SQL窗口中建立連接和查詢

select dblink_connect(‘t_connect’,’dbname=test2 host=localhost port=5432 user=postgres password=postgres’);

select * from dblink(‘t_connect’,’select * from tablea’)  as t2(id int,name varchar(10));

image

上面的select語句其實是利用了dblink(text,text)和dblink_connect(text,text)函數

 

兩個數據庫中表的連接其實也類似;還是在test1數據庫的SQL窗口查詢

select a.*,b.name from tablea a inner join

(select * from dblink('t_connect','select * from tablea') as t2(id int,name varchar(10))) b

on a.id=b.id

image

就是把這個查詢select * from dblink('t_connect','select * from tablea') as t2(id int,name varchar(10))當成一個表就可以了。

很類似SQL Server中鏈接服務器,查詢鏈接服務器的sql,之前隨筆中應該寫過SQL Server鏈接的MySQL,通過SSMS查詢MySQL中的數據。

 

Postgres以前我也沒接觸過,不過工作中需要使用Postgres,有應用的需求,總要解決!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM