I am trying to run the following query in postgresql to insert data to a table from the subquery results of two tables.
Here are my three sample tables -
CREATE TABLE a (
id SERIAL PRIMARY KEY
data int
);
CREATE TABLE b (
id SERIAL PRIMARY KEY,
aID INT
data INT
);
CREATE TABLE c (
id SERIAL PRIMARY KEY,
aID INT,
bID INT,
name VARCHAR
);
I'm using the following query to do an INSERT into the c table -
INSERT INTO c (
aID,
bID,
name)
VALUES (
(SELECT id FROM a WHERE data=$1),
(SELECT id FROM b WHERE data=$2 AND aID=(SELECT id FROM a WHERE data=$1)),
$3)
ON CONFLICT (bID)
DO NOTHING;
I was wondering whether it was possible to use the results of the first SELECT from the a table in the second subquery to reduce data access. I'm not sure this is the right way to go. Any help would be appreciated.
a.data = $2. Is this a typo?