为简化一点,我有一个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)
如何?
答案 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;
这也可以解决同一产品在包装中多次出现的问题。