SQL更新从另一个表中选择的表

时间:2015-03-26 14:34:50

标签: mysql sql sql-update sum

为简化一点,我有一个product表:

PRODUCT
---
id
type (FK)

相应的1:1 type表格(product.type -> type.id):

TYPE
---
id
weight

然后我有一张packaging表。

PACKAGING
---
id
total_weight

包装可以包含一种或多种产品。 packaging.total_weight是一个便利字段,用于存储其包含的产品的所有权重的总和。

n * m packaging*products关系由nm_packaging_product表实现:

NM_PACKAGING_PRODUCT
---
packaging_id (PK, FK)
product_id (PK, FK)

现在,有人可以改变产品的重量。发生这种情况时,我想更新计算新权重的packaging.total_weight。我所知道的是@product_id的重量已经改变了。

我想UPDATE使用一个SQL。像:

UPDATE
    PACKAGING
SET
    total_weight=???
WHERE
    id IN (SELECT packaging_id FROM NM_PACKAGING_PRODUCT WHERE product_id = @prodotto_id)

如何?

2 个答案:

答案 0 :(得分:1)

试试这个

UPDATE
    PACKAGING
SET
    total_weight= (select sum(weight) from TYPE,NM_PACKAGING_PRODUCT, PRODUCT
                   where type.id = product.type and product.id= nm_product.product_id and 
                   nm_packaging_product.packaging_id = packaging.id  )
WHERE
    id IN (SELECT packaging_id FROM NM_PACKAGING_PRODUCT WHERE product_id = @prodotto_id)

答案 1 :(得分:0)

重新计算所有权重并仅重置更改的权重:

UPDATE PACKAGING p JOIN
       (SELECT packaging_id, SUM(weight) as total_weight
        FROM NM_PACKAGING_PRODUCT pp
        GROUP BY packing_id
       ) ppw
       ON p.packaging_id = ppw.packaging_id    
    SET total_weight = ppw.total_weight
    where p.total_weight <> ppw.total_weight;

这也可以解决同一产品在包装中多次出现的问题。