PostgreSQL join across 2 databases

 ̄綄美尐妖づ 提交于 2020-01-04 06:02:12

问题


I am new to PostgreSQL. I have 2 databases in PostgreSQL 9.0, db1 and db2, and with db2 I have read only access. I want to create a stored function that would be otherwise easily accomplished with a JOIN or a nested query, something PostgreSQL can't do across databases.

In db1, I have table1 where I can query for a set of foreign keys keys that I can use to search for records in a table2 in db2, something like:

SELECT * from db2.table2 WHERE db2.table2.primary_key IN (
    SELECT db1.table1.foreign_key FROM db1.table1 WHERE
        db1.table1.primary_key="whatever");

What is the best practice for doing this in Postgres? I can't use a temporary tables in db2, and passing in the foreign keys as a parameter in a stored function running in db2 doesn't seem like a good solution.

Note: the keys are all VARCHAR(11)


回答1:


You'll want to look into the db_link contrib.

As an aside if you're familiar with C, there also is a cute functionality called foreign data wrappers. It allows to manipulate pretty much any source using plain SQL. Example with Twitter:

SELECT from_user, created_at, text FROM twitter WHERE q = '#postgresql';


来源:https://stackoverflow.com/questions/6295837/postgresql-join-across-2-databases

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!