如何将我的select语句转换为更新语句?

时间:2011-04-12 18:29:03

标签: mysql sql

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;

上述选择语句总结了每个报价中所有产品的净成本,并按报价编号显示总和。

我在报价表中添加了net_cost_total字段。我想用每个报价中的net_cost总数更新所有报价。查询失败,它说GROUP语法不好,我不知道怎么回事。

3 个答案:

答案 0 :(得分:5)

试试这个:

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 

答案 1 :(得分:1)

尝试:

UPDATE quotes
INNER JOIN (
    SELECT SUM(qitems.net_cost_ext) AS s
    FROM qitems
    GROUP BY qitems.qid
  ) q USING(qid)
SET net_cost_total = q.s

(灵感来自上一篇MySQL评论here

答案 2 :(得分:0)

使用标准SQL:

UPDATE quotes
   SET net_cost_total = (
                         SELECT SUM(net_cost_ext)
                           FROM qitems
                          WHERE quotes.qid = qitems.qid
                        )
 WHERE EXISTS (
               SELECT *
                 FROM qitems
                WHERE quotes.qid = qitems.qid
              );