如何在更新查询中设置两列的总和

时间:2015-08-19 07:54:41

标签: mysql

**

  

如何在更新查询中设置两列的总和

**

INSERT INTO account (id, cid, stock, stockAvailable, sumStock) VALUES (1, '1','10', '20', '0'), (2,'1', '10', '20', '0');

    UPDATE account SET sumStock=SUM(stock)  FROM account where cid= '1'

1 个答案:

答案 0 :(得分:0)

一种可行的方法是使用不同的别名引用同一个表并加入它们:

UPDATE account AS a1 INNER JOIN ( SELECT SUM(stock) AS count FROM account ) AS a2 ON a1.cid = a2.cid SET a1.sumStock=a2.count WHERE a1.cid= '1'