0

我需要帮助来更新表中的余额列。使用更新命令

customer_master 中的余额列

customer_master > custcode,余额

它需要根据两个表中的值进行更新

Bookings > custcode, bookingamount

应收账款 > custcode、amountrecd

对于客户代码,余额为 bookingamount - amountrecd

该命令将在 mysql 和 postgresql 中应用。

它可以适用于单个客户,例如(对于 custcode ='A1234XXXXX'),也可以适用于 customer_master 中存在的所有客户。

我在“更新两张表的余额”上尝试了谷歌,但到目前为止没有运气。

谢谢

4

2 回答 2

2

对于 MySQL,你可以连接多个表,即使它是一个UPDATE语句。我使用LEFT JOIN是因为有可能在表格custcode上还没有记录。receivables

UPDATE  customer_master a
        LEFT JOIN bookings b
            ON a.custcode = b.custcode
        LEFT JOIN receivables c
            ON a.custcode = c.costcode
SET     a.balance = COALESCE(b.bookingamount, 0) - COALESCE(c.amountrecd, 0) 
-- WHERE a.custcode = 'A1234XXXXX'

后续问题: custcode 可以在bookings和上包含多条记录receivables吗?如果是这样,我会更新答案。

于 2012-10-20T05:53:36.207 回答
1

我的看法有点(可能)在顶部皮带和牙套上

UPDATE  customer_master a
        LEFT JOIN (select custcode, sum(COALESCE(bookingamount, 0)) AS bookingamount 
                   from bookings group by custcode) b
            ON a.custcode = b.custcode
        LEFT JOIN (select custcode, sum(COALESCE(amountrecd, 0)) AS amountrecd 
                   from receivables group by custcode) c
            ON a.custcode = c.custcode
SET     
         a.balance = COALESCE(b.bookingamount, 0) - COALESCE(c.amountrecd, 0) 
-- WHERE a.custcode = 'A1234XXXXX'
于 2012-10-20T06:03:23.150 回答