麻烦在INSERT上使用WITH("缺少FROM子句条目")

时间:2014-06-16 06:37:55

标签: sql postgresql

我正在尝试使用之前CTE的信息构建一个新行,但我似乎无法正确理解语法。

BEGIN;
UPDATE users
SET balance = balance - 10
WHERE user_id = 1;

WITH te AS (
  SELECT accountInsertOrSelect('the.hound', 'farcebook', 'rong') AS account_id
), tr AS (
  SELECT account_id FROM accounts
  WHERE user_id = 1
  AND provider = 'farcebook'
  LIMIT 1
)
INSERT INTO tips (tipper_id, tippee_id, amount)
VALUES (te.account_id, tr.account_id, 10);
COMMIT;

给出错误missing FROM-clause entry for table "te"

2 个答案:

答案 0 :(得分:2)

当您尝试插入时,需要在FROM CLAUSE中指定CTE,如下所示:

INSERT INTO tips (tipper_id, tippee_id, amount) VALUES
((SELECT account_id FROM te), (SELECT account_id from tr), 10)

答案 1 :(得分:1)

INSERT INTO tips (tipper_id, tippee_id, amount)
select 
    (select account_id from te), 
    (select account_id from tr), 
    10

INSERT INTO tips (tipper_id, tippee_id, amount)
select te.account_id, tr.account_id, 10
from te cross join tr