One fix is to change the values
to a select
:
INSERT INTO emailevents (shopid, userid, emailid, campaignid, variationid, type, createdon)
select $1,
(SELECT id FROM users WHERE mongoid=$2),
(SELECT id FROM emails WHERE mongoid=$3),
(SELECT id FROM campaigns WHERE mongoid=$4) AS cid,
(SELECT id FROM campaignvariations WHERE templateid=(SELECT id FROM templates WHERE mongoid=$5) AND campaignid=cid),
$6,
to_timestamp($7);
I prefer using insert . . . select
rather than insert . . . values
in general.
You might be able to just remove the as cid
if Postgres supports subqueries in the values
statement.
EDIT:
The above fixes the as
problem, but not the overall problem. Let's use select
and move most of the subqueries to the from
clause:
INSERT INTO emailevents (shopid, userid, emailid, campaignid, variationid, type, createdon)
select const.shopid, u.id, e.id, c.id
(SELECT id
FROM campaignvariations
WHERE templateid=(SELECT id FROM templates WHERE mongoid=$5) AND campaignid=c.id
),
const.type,
const.createdon
from (select $1 as shopid, $6 as type, to_timestamp($7) as createdon) const left outer join
(SELECT id FROM users WHERE mongoid=$2) u cross join
(SELECT id FROM emails WHERE mongoid=$3) e cross join
(SELECT id FROM campaigns WHERE mongoid=$4) c;