15

这个位工作得很好:

 SELECT products_id, sum(attributes_stock) 
 FROM products_attributes 
 GROUP BY products_id

它将attributes_stock列中的所有字段组加在一起。

我遇到的问题是让这个结果更新另一个表中的另一个列。

这就是我所拥有的:

 UPDATE products, products_attributes 
 SET products.products_quantity = sum(products_attributes.attributes_stock) GROUP BY products_attributes.products_id 
 WHERE products.products_id = products_attributes.products_id

非常感谢任何建议。

4

3 回答 3

28

您不能group by在更新语句中使用内部。您需要使用子选择来进行分组。

像这样的东西:

UPDATE products p,( SELECT products_id, sum(attributes_stock)  as mysum
                   FROM products_attributes GROUP BY products_id) as s

   SET p.products_quantity = s.mysum
  WHERE p.products_id = s.products_id
于 2013-01-22T23:43:46.537 回答
7

有些人更喜欢连接操作的新式JOIN ... ON语法,而不是 WHERE 子句中的逗号运算符和连接谓词:

UPDATE products p
  JOIN ( SELECT q.products_id
              , SUM(q.attributes_stock) AS sum_attr
           FROM products_attributes q
          GROUP BY q.products_id
       ) r
    ON r.products_id = p.products_id
   SET p.products_quantity = r.sum_attr
于 2013-01-23T00:12:35.423 回答
1

试试这个:

update 
    products, 
    (select 
        products_id, sum(attributes_stock) as sumAttr
     from products_attributes
     group by products_id) as a
set
    products.products_cuantity = a.sumAttr
where
    products.products_id = a.products_id
于 2013-01-22T23:46:52.593 回答