我收到错误:错误号码:1242 子查询返回超过1行
因为我的UPDATE
子查询会产生重复值。我知道DISTINCT
和GROUP BY
可以删除SELECT
查询中的重复值。如何在UPDATE
查询中修复它。我的问题是这里
UPDATE
product_stock AS S
LEFT JOIN
product_purchase_item AS I
ON
S.product_id=I.product_id AND S.product_size=I.product_size
LEFT JOIN
product_purchases AS P
ON
I.product_purchase_item_id=P.product_purchase_item_id
SET
S.product_size_quantity=S.product_size_quantity+I.quantity
WHERE
S.product_id=?
AND
S.product_size=?
假设,如果我在SELECT
查询
SELECT
S.*
FROM
product_stock AS S
LEFT JOIN
product_purchase_item AS I
ON
S.product_id=I.product_id AND S.product_size=I.product_size
LEFT JOIN
product_purchases AS P
ON
I.product_purchase_item_id=P.product_purchase_item_id
查询返回
product_stock_id product_id product_size product_quantity 10 216 1 1 10 216 1 1 11 216 5 1
但我需要(只需一个DISTINCT
关键字就可以在SELECT
查询中执行此操作)
product_stock_id product_id product_size product_quantity 10 216 1 1 11 216 5 1
但是,如何在我的UPDATE
子查询中检索上述数据(UNIQUE VALUES)?是否可以在DISTINCT
查询中使用UPDATE
关键字或类似内容?
答案 0 :(得分:0)
如果数据真的相同,您可以简单地使用"min()"
而不使用group by / distinct
UPDATE
product_stock AS S
LEFT JOIN
product_purchase_item AS I
ON
S.product_id=I.product_id AND S.product_size=I.product_size
LEFT JOIN
product_purchases AS P
ON
I.product_purchase_item_id=P.product_purchase_item_id
SET
-- CHANGE HERE ===============================>
S.product_size_quantity=S.product_size_quantity+MIN(I.quantity)
WHERE
S.product_id=?
AND
S.product_size=?
答案 1 :(得分:0)
这应该可以解决问题。是否有理由包含product_purchases表,因为它在您的查询中似乎是多余的?
UPDATE product_stock SET product_size_quantity = product_size_quantity + I.quantity
from product_stock
INNER JOIN (select product_id, product_size, sum(quantity) from product_purchase_item group by product_id, product_size) AS I
ON product_stock.product_id=I.product_id AND product_stock.product_size=I.product_size
WHERE product_stock.product_id=?
AND product_stock.product_size=?