繁体   English   中英

在 postgresql 中从另一个表更新列的问题

[英]Problems with updating column from another table in postgresql

我的数据库是 postgresql。 我有 4 个表,需要将“payment_option”记录的 id 复制到“结算”表中的列。

关于模型的快速信息:帐户有 N 个发票,发票有 N 个结算。 结算具有四种付款选项之一,这些选项当前由带有字符串的列(PAYPAL、STRIPE、LEGACY、WIREPAYMENT)确定。 帐户有 N 个 payment_options(在当前状态下总是 4 个。每种类型一次)并且这些付款选项中的每一个在列中再次具有这些类型之一作为字符串(PAYPAL、STRIPE、LEGACY、WIREPAYMENT)。 我需要添加从结算表指向payment_option表的fkey,我可以找到结算->发票->账户->payment_option

为此,我需要进行多次连接并执行诸如“UPDATE JOIN”之类的操作,但由于某种原因我失败了。 我的声明更新了第一个payment_option id 上的所有settlement.payment_option_id,而不是通过帐户和发票表绑定的payment_option id。

update settlement 
set payment_option_id = P.id
from payment_option as P 
inner join invoice as I on P.account_id = I.account_id
inner join settlement as S on S.invoice_id = I.id
where S.payment_option_type = P.type;

如何正确写,有什么问题? 我认为问题出在“SET”中,因为当我使用以下连接编写选择时,它按预期工作

谢谢卢卡斯

您在FROM子句中重复对settlement的引用似乎很奇怪。 也许你打算:

update settlement s
    set payment_option_id = P.id
    from payment_option P join
         invoice I
         on P.account_id = I.account_id
    where S.payment_option_type = P.type and S.invoice_id = I.id

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM