一种解决方法是将 更改values
为 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);
我更喜欢使用insert . . . select
而不是insert . . . values
一般。
您也许可以只删除语句中的as cid
if Postgres 支持子查询values
。
编辑:
以上解决了as
问题,但不是整体问题。让我们使用select
大部分子查询并将其移动到from
子句:
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;