这一点很有效:
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
任何建议都非常感谢。
答案 0 :(得分:26)
您无法在更新语句中使用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
答案 1 :(得分: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
答案 2 :(得分: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