我有这个数据库:
-
表1 产品:ID、名称、total_sales
-
表2 Products_sales:id_product、id_user、价格
我想使用此查询更新列"total_sales">
UPDATE products p SET total_sales = (SELECT SUM(price) AS totalPrice
FROM `products_sales` WHERE id_product = p.id GROUP BY id_product)
但是,如果一个产品没有任何销售,我会收到此错误:
#1048 - Column 'total_sales' cannot be null
当产品没有销售时,如何避免此错误?
也许使用回退值?
作为后备,您可以将零与COALESCE
UPDATE
products AS p
INNER JOIN (
SELECT id_product, COALESCE(SUM(price), 0) AS totalPrice
FROM `products_sales`
GROUP BY id_product
) AS pSub ON p.id = pSub.id_product
SET p.total_sales = pSub.totalPrice;