Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL Update using sum() result across multiple tables

Tags:

sql

php

mysql

pdo

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.

like image 778
windywah Avatar asked Jan 22 '13 23:01

windywah


2 Answers

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
like image 65
Ray Avatar answered Sep 18 '22 11:09

Ray


Some favor the newer-style JOIN ... ONsyntax 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
like image 29
spencer7593 Avatar answered Sep 18 '22 11:09

spencer7593