我有一個函數:Postgres的功能,插入和更新
create function fn_name_here() returns int as
$$
begin
with c as (
Select a1.accounts_id,sum(a2.quantity * a2.unit_price) as MRR
from account_subscriptions a1
inner join order_item a2 on a1.subscription_id = a2.account_subscriptions_id
group by a1.accounts_id
)
update summary s set MRR = c.MRR
from c
where c.accounts_id = s.accounts_id;
return 0;
end;
$$ language plpgsql
與查詢,我得到accounts_id
和mrr
,並通過對比accounts_id
更新在summary
表mrr
。
但我也需要一個新行accounts_id
和mrr
在summary
表中插入如果accounts_id
已經不存在在那裏,但它拋出一個錯誤。
,當我與此查詢編輯它,並調用函數
UPDATE dummy s SET mrr = c.MRR from c WHERE c.accounts_id = s.accounts_id ;
IF NOT FOUND THEN
INSERT INTO dummy (mrr,accounts_id)
select c.mrr,c.accounts_id from c;
END IF;
它引發錯誤
relation "c" does not exist
LINE 1: ...TO dummy (mrr,accounts_id) select c.mrr,c.accounts_id from c
爲什麼[tag:mysql]標記? – Jens
請更新帖子,您收到錯誤 –
您正在使用哪個版本的postgres? –