3

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

2 回答 2

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
于 2012-07-19T07:15:54.260 回答
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
于 2012-07-19T07:16:27.487 回答