This bits working great:
SELECT products_id, sum(attributes_stock)
FROM products_attributes
GROUP BY products_id
Which adds together all the groups of fields in the attributes_stock
column.
What I am having trouble with is getting this result to UPDATE another column in another table.
This is what I have:
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
Any advice greatly appreciated.
You can't use a group by
inside an update statement. You'll need to use an sub select to do the grouping.
Something like this:
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
Some favor the newer-style JOIN ... ON
syntax for a join operation, vs. the comma operator and the join predicate in the WHERE clause:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With