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

时间:2012-07-19 07:08:03

标签: mysql sum sql-update temp-tables mysql-error-1111

我需要获取子行的总和值并在父行上更新该数据。 我已经得到了如下所示,但遇到错误#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);

2 个答案:

答案 0 :(得分:2)

您需要做的是按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

答案 1 :(得分:2)

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