我可以在UPDATE表中使用GROUP BY MySQL事务

时间:2013-12-10 15:46:15

标签: mysql

我有两张桌子:

m3clients
client    balance
joe       0
mark      0
jeff      0

m3orders
client    balance
joe       -100
joe       50
joe       -45
mark      -10
mark      5
jeff      60

我需要使用附加到其名称的余额总和来更新m3clients表余额字段。

所以,它会读到这样的东西:

m3clients
joe    -95
mark   -5
jeff   60

在update语句中我将GROUP BY语句放在哪里?

UPDATE m3clients
INNER JOIN m3orders ON (m3orders.client = m3clients.client)
SET m3clients.balance = m3orders.balance

2 个答案:

答案 0 :(得分:0)

计算子查询中每个客户端的余额,并将结果与​​表m3clients结合起来。

UPDATE  m3clients
        INNER JOIN 
        (
            SELECT client, SUM(balance) balance
            FROM    m3orders 
            GROUP   BY client
        ) cal ON m3clients.client = cal.client
SET     m3clients.balance = cal.balance

答案 1 :(得分:0)

试试这样:

UPDATE m3clients m
INNER JOIN (
   SELECT client,SUM(balance) as bal
   FROM m3orders 
   GROUP by client) a ON m.client = a.client
SET m.balance = a.bal

这使用子查询为每个客户执行余额的平衡,然后将其与m3clients表连接,以便能够使用计算的余额更新它。