【问题标题】:Problems with updating column from another table in postgresql从 postgresql 中的另一个表更新列的问题
【发布时间】:2020-01-03 19:30:03
【问题描述】:

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

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

为此,我需要进行多次连接并执行“UPDATE JOIN”之类的操作,但由于某种原因我失败了。我的语句更新了第一个 payment_option 的 id 上的所有结算.payment_option_id,而不是通过 account 和 invoice 表绑定的 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”中,因为当我使用以下连接编写选择时,它按预期工作

谢谢卢卡斯

【问题讨论】:

    标签: sql postgresql join sql-update


    【解决方案1】:

    您在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
    

    【讨论】:

    • 谢谢。这解决了我的问题。我还没有写过这样的声明
    猜你喜欢
    • 2012-11-08
    • 1970-01-01
    • 2021-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-18
    • 1970-01-01
    • 2022-01-23
    相关资源
    最近更新 更多