0

我收到一个错误:错误号:1242 子查询返回超过 1 行

因为 MyUPDATE的子查询产生重复值。我知道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子查询中检索上述数据(唯一值)?是否可以DISTINCT在我的UPDATE查询中使用关键字或类似的任何内容?

4

2 回答 2

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=?
于 2013-08-30T22:16:10.937 回答
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=?
于 2013-08-30T16:46:19.120 回答