如何在UPDATE查询中获取DISTINCT / GROUP BY行为

时间:2013-08-30 16:42:35

标签: mysql sql sql-update

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

因为我的UPDATE子查询会产生重复值。我知道DISTINCTGROUP 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关键字或类似内容?

2 个答案:

答案 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=?