MySQL:使用两个表的总和更新值

时间:2016-02-09 20:53:40

标签: mysql sql

我有一个像这样的表格设置

负债

Id | CustomerId | liabilities
---------------------------
9    90           1000
...

付款

Id | CustomerId | Payment
---------------------------
3    90           2500
4    91           1000
...

客户

Id | balance
---------------------------
90   1500
91   1000
...

如您所见,客户的余额是其所有付款减去所有负债总和的总和。什么是更新余额的SQL查询?

1 个答案:

答案 0 :(得分:2)

您可以使用带有UPDATE操作的LEFT JOIN语句对包含PaymentsLiabilities聚合的派生表执行此操作:

UPDATE Customer AS c
LEFT JOIN (
  SELECT CustomerId, SUM(Payment) AS TotalPayment
  FROM Payments
  GROUP BY CustomerId
) AS p ON c.Id = p.CustomerId
LEFT JOIN (
  SELECT CustomerId, SUM(liabilities) AS TotalLiabilities
  FROM Liabilities
  GROUP BY CustomerId
) AS l ON c.Id = l.CustomerId  
SET balance = COALESCE(TotalPayment, 0) - COALESCE(TotalLiabilities, 0)

Demo here

或者,您可以在UPDATE语句中使用相关子查询:

UPDATE Customer AS c 
SET balance = COALESCE((SELECT SUM(Payment) 
                        FROM Payments 
                        WHERE CustomerId = c.Id) , 0)
              - 
              COALESCE((SELECT SUM(liabilities) 
                        FROM Liabilities 
                        WHERE CustomerId = c.Id)  , 0)

Demo here