0

I'm running PostgreSQL 11.8 in a Docker container. I have two databases: website_db and testdb.

website_db has a products table with id, product_name, colour, product_size columns

testdb has a table called users with id, username, password

I'm using website_db and I want to UNION columns from the users table in the testdb database. I can get this to work in MySQL but am struggling with Postgres. Here's my attempt:

SELECT * FROM products WHERE product_name = 'doesntexist' OR 1=1 UNION SELECT null,username,password,null FROM testdb.users;

I get this error back:

ERROR:  relation "testdb.users" does not exist
LINE 1: ...1=1 UNION SELECT null,username,password,null FROM testdb.use...

Does anyone know what I have to do to fix my query?

hgb123
  • 11,887
  • 3
  • 15
  • 33

1 Answers1

0

You can do it using dblink:

create database first;
create database second;
\c first;

create table products
(
    id serial not null
        constraint products_pk
            primary key,
    product_name varchar(50) not null
);


INSERT INTO public.products (id, product_name) VALUES (1, 'first_db');

\c second;

create table products
(
    id serial not null
        constraint products_pk
            primary key,
    product_name varchar(50) not null
);


INSERT INTO public.products (id, product_name) VALUES (1, 'sec_db');

-- dblink -- executes a query in a remote database 
create extension dblink;

-- change queries and creds
SELECT id, product_name FROM products
UNION ALL
SELECT * FROM dblink('dbname=first user=root password=root', 'SELECT id, product_name FROM products') AS tb2(id int, product_name text);
Danila Ganchar
  • 8,684
  • 12
  • 42
  • 65