数据库
首页 > 数据库> > MySQL:如何将子表的SUM()值更新为同一表中的父行?

MySQL:如何将子表的SUM()值更新为同一表中的父行?

作者:互联网

我需要获取子行的总和,并更新父行上的数据.
我已经为此得到了如下所示,但是遇到了错误#1111(无效使用组函数).

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);

解决方法:

您需要做的是按ID分组,以将每个父ID的子代和分开.您将需要使用子选择来完成此操作.

另外,您无需创建临时表.只需将聚合包装在子选择中(按parent_id分组),然后将子选择加入主表即可:

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

标签:sum,sql-update,temp-tables,mysql-error-1111,mysql
来源: https://codeday.me/bug/20191101/1980857.html