Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

I have a problem with join 2 database. First.. I tried use this query:

   SELECT * 
     FROM my_db1.table1 tb1 
LEFT JOIN my_db2.table2 tb2 ON tb2.code = tb1.code

I get the following error:

schema "my_db2" does not exist.

So I tried:

SELECT * 
  FROM dblink('my_db2', 'SELECT * FROM table2')

But it still doesn't work.
What should I do, to select from two tables that are in different databases?

share|improve this question

This should work with dblink for two databases in the same cluster where the calling user has the necessary privileges to both. Call from a connection to your db1:

SELECT * 
FROM   table1 tb1 
LEFT   JOIN (
   SELECT *
   FROM   dblink('dbname=db2','SELECT id, code FROM table2')
   AS     tb2(id int, code text);
   ) USING (code)

Two things were missing: the connection string and the column definition list.

However, I would encapsulate access to a foreign table in a view or table function. I quote the manual:

A convenient way to use dblink with predetermined queries is to create a view. This allows the column type information to be buried in the view, instead of having to spell it out in every query.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.