Search code examples
mysqlsumsql-updatetemp-tablesmysql-error-1111

MySQL: How to update SUM() values of children to a parent row in the same table?


I need to get the sum values of my child rows and update that data on the parent row. I've got this for as shown below but ran into error #1111 (Invalid use of group function).

CREATE TEMPORARY TABLE cms_ladu_temp LIKE cms_ladu;

INSERT INTO cms_ladu_temp SELECT * FROM cms_ladu WHERE parent_id IN (326,500);

UPDATE 
    cms_ladu 
INNER JOIN
    cms_ladu_temp
ON
    cms_ladu_temp.parent_id=cms_ladu.id 
SET  
    cms_ladu.child_packaging_units_in=SUM(cms_ladu_temp.packaging_units_in), 
    cms_ladu.child_net_weight_in=SUM(cms_ladu_temp.net_weight_in) 
WHERE 
    cms_ladu.id IN (326,500);

Solution

  • What you need to do is group by the id to separate the child sums for each parent id. You will need to use a subselect to accomplish this.

    Also, you don't need to create a temporary table. Just wrap the aggregation in a subselect (grouping by parent_id), and join the subselect onto the main table:

    UPDATE 
        cms_ladu a
    INNER JOIN
    (
        SELECT   parent_id, 
                 SUM(packaging_units_in) AS pui,
                 SUM(net_weight_in) AS nwi
        FROM     cms_ladu
        WHERE    parent_id IN (326,500)
        GROUP BY parent_id
    ) b ON a.id = b.parent_id
    SET 
        a.child_packaging_units_in = b.pui,
        a.child_net_weight_in = b.nwi