postgres=# CREATE TABLE userinfo (id int primary key, name text); CREATE TABLE postgres=# INSERT INTO userinfo VALUES (1, 'Eric'), (2, 'Tom'); INSERT 0 2 postgres=# SELECT * FROM userinfo; id | name ----+------ 1 | Eric 2 | Tom (2 rows)
postgres=# CREATE DATABASE localdb; CREATE DATABASE postgres=# \c localdb You are now connected to database "localdb" as user "japin". localdb=# CREATE TABLE local_test (id serial primary key, ival int default 0, create_time timestamptz not null default now()); CREATE TABLE localdb=# INSERT INTO local_test(ival) VALUES (1), (2), (3), (4); INSERT 0 4 localdb=# SELECT * FROM local_test; id | ival | create_time ----+------+------------------------------- 1 | 1 | 2019-05-09 15:03:44.701121+08 2 | 2 | 2019-05-09 15:03:44.701121+08 3 | 3 | 2019-05-09 15:03:44.701121+08 4 | 4 | 2019-05-09 15:03:44.701121+08 (4 rows)
postgres=# SELECT u.id, name, create_time FROM userinfo u JOIN dblink('local_dblink_test', 'SELECT * FROM local_test;') AS lt(id int, ival int, create_time timestamptz) on u.id = lt.id; id | name | create_time ----+------+------------------------------- 1 | Eric | 2019-05-09 15:03:44.701121+08 2 | Tom | 2019-05-09 15:03:44.701121+08 (2 rows)
为了方便,我们可以为 dblink 的执行创建一个视图。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
postgres=# CREATE VIEW v_localdb_test AS SELECT * FROM dblink('local_dblink_test', 'SELECT * FROM local_test;') AS lt(id int, ival int, create_time timestamptz); CREATE VIEW postgres=# SELECT * FROM v_localdb_test ; id | ival | create_time ----+------+------------------------------- 1 | 1 | 2019-05-09 15:03:44.701121+08 2 | 2 | 2019-05-09 15:03:44.701121+08 3 | 3 | 2019-05-09 15:03:44.701121+08 4 | 4 | 2019-05-09 15:03:44.701121+08 (4 rows)
postgres=# SELECT u.id, name, create_time FROM userinfo u JOIN v_localdb_test v ON u.id = v.id; id | name | create_time ----+------+------------------------------- 1 | Eric | 2019-05-09 15:03:44.701121+08 2 | Tom | 2019-05-09 15:03:44.701121+08 (2 rows)
备注: 在 local_test 表中 id 字段类型为 serial,但是在通过 dblink 查询时返回的结果类型不能使用 serial 类型。
postgres=# SELECT u.id, name, create_time FROM userinfo u JOIN dblink('remote_dblink_test', 'SELECT * FROM remote_test;') AS t(id int, ival int, create_time timestamptz) ON u.id = t.id; id | name | create_time ----+------+------------------------------- 1 | Eric | 2019-05-09 15:34:42.599409+08 2 | Tom | 2019-05-09 15:34:42.599409+08 (2 rows)