Search code examples
sqlpostgresqlcross-database

Cross Database Query in PostgreSQL


I am trying to build a query in Postgres. My background is in SQL Server so, I'm having some syntactical challenges. My query needs to hit two seperate databases on two separate servers. I need to do a join between the datasets. Essentially, I have a table with user login activity in db1. A entry gets added each time a user logs into the website. On db2, I have a table with purchases. For each day, I need to see: how many people logged in and how many of the users that logged in made a purchase.

My tables look like this:

Logins                Purchases
---------             ---------
ID                    User_ID
User_ID               Amount
LoginDate 

This would be easy if my Purchases table had a date field on it. But it doesn't. So, currently, I'm trying the following:

SELECT 
  // Somehow get the number of logins for the given day here
  // Somehow I need to get the number of purchases for the given day here      
  TO_CHAR(TO_TIMESTAMP((LoginDate/1000) - 14400), 'MM/DD/YYYY') AS the_day
FROM 
  db1.Logins AS t1,
  db2.Purchases as t2
GROUP BY the_day
ORDER BY the_day;

How do I get the number of logins and purchases for a each day in Postgres? Thank you!


Solution

  • Cross-database queries are not supported by PostgreSQL. Most people who want "cross-database" queries land up instead using a single database with multiple schema within it. I'm not sure about MS-SQL, but MySQL's "database"s are more like PostgreSQL "schema".

    If you require cross-database queries you must use DBLink or postgres-fdw. Or you can replicate the data - look into Londiste, Slony-I, or a simple cronjob.