SELECT quotes.qid, SUM(qitems.net_cost_ext)
FROM quotes, qitems
WHERE quotes.qid = qitems.qid
GROUP BY qitems.qid;

UPDATE quotes, qitems
SET quotes.net_cost_total = SUM(qitems.net_cost_ext)
WHERE quotes.qid = qitems.qid
GROUP BY qitems.qid;

上面的select语句汇总每个报价上所有产品的净成本,并按报价编号显示总和。
我在报价表中添加了一个“净成本”字段。我想用每个报价的净成本总额更新所有报价。查询失败,它说组语法不好,我不知道该怎么做。

最佳答案

试试这个:

UPDATE quotes AS q
        JOIN (SELECT quotes.qid,
                         SUM(qitems.net_cost_ext) AS SUM
                  FROM   quotes,
                         qitems
                  WHERE  quotes.qid = qitems.qid
                  GROUP  BY qitems.qid) AS d
         ON d.qid = q.qid
SET    q.net_cost_total = d.SUM

关于mysql - 如何将我的选择语句转换为更新语句?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5639888/

10-09 19:24