在 MySQL 中使用多个连接进行更新

问题描述 投票:0回答:2

我在更新 MySQL 数据库 (InnoDB) 中的表时遇到问题。

我有三张桌子

1-

orders
桌子

订单号 用户名 状态
7 4 弯曲
8 4 弯曲

2-

orderedProducts

订单号 产品编号 数量
7 22 1
7 24 1
8 22 2
8 20 1

3-

products

产品编号 数量 已购买
20 1 3
22 0 1
24 1 1

现在当我执行以下查询时:-


UPDATE 
    orders JOIN 
    orderedProduct ON orders.orderId=orderedProducts.orderedId JOIN 
    products ON products.productId=orderedProducts.productId
SET
    products.quantity=products.quantity+orderedProducts.quantity,
    products.purchased=products.purchased-orderedProducts.quantity,
    orders.status="canceled"
WHERE
    orders.userId=4;

或者这个


UPDATE 
    orders, orderedProducts, products 
SET
    products.quantity=products.quantity+orderedProducts.quantity
    products.purchased=products.purchased-orderedProducts.quantity,
    orders.status="canceled"
WHERE
    orders.userId=4 AND products.productId=orderedProducts.productId;

我期望结果是这样的:-

产品

产品编号 数量
20 2
22 3
24 2

但结果如下:-

产品编号 数量
20 2
22 1
24 2

有人知道发生了什么事吗?

mysql sql sql-update multiple-tables
2个回答
0
投票

有人知道发生了什么事吗?

orderedProducts 表中有多行相同的 productId 等结果。

以下查询将为您提供正确的结果,如 DBFIDDLE

UPDATE products
SET quantity = quantity + (
  SELECT SUM(quantity)
  FROM orderedProducts
  WHERE productId = products.productId
  AND orderId IN (
    SELECT orderId
    FROM orders
    WHERE userId = 4
  )
);

输出:

select * from products;

产品编号 数量
20 2
22 3
24 2

好吧,如果你想使用

join
做同样的事情; 你可以按照这个 DBFIDDLE:

    UPDATE products
JOIN (
    SELECT orderedProducts.productId, SUM(orderedProducts.quantity) AS total_quantity
    FROM orderedProducts
    JOIN orders ON orderedProducts.orderId = orders.orderId
    WHERE orders.userId = 4
    GROUP BY orderedProducts.productId
) AS ordered
ON products.productId = ordered.productId
SET products.quantity = products.quantity + ordered.total_quantity;

这也应给出预期的输出

更新:

根据您的评论:

在 Products 表中,还有一列我想修改 (购买)。另外,在订单表中,有一列我想要 修改(状态)。我认为在这种情况下最好使用 JOIN,但是 它会忽略重复的 productId。有没有具体的公式 不忽略重复值?

您可以按以下方式更新它:

UPDATE products p
JOIN orderedProducts op ON p.productId = op.productId
JOIN orders o ON op.orderId = o.orderId
SET p.quantity = p.quantity + op.quantity,
p.purchased = p.purchased + op.quantity,
o.status = 'Processed'
WHERE o.userId = 4;

0
投票

此查询将为您提供每个产品的更新数量:

select p.productId, sum(distinct p.quantity) + sum(op.quantity)
from products p
inner join orderedProducts op on op.productId = p.productId
inner join orders o on o.orderId = op.orderId
WHERE o.userId=4
group by p.productId

使用之前的查询,更新后的查询可能如下:

Update products p
inner join (
  select p.productId, sum(distinct p.quantity) + sum(op.quantity) as newQuantity
  from products p
  inner join orderedProducts op on op.productId = p.productId
  inner join orders o on o.orderId = op.orderId
  WHERE o.userId=4
  group by p.productId
) s on s.productId = p.productId
set quantity = s.newQuantity

这里演示

© www.soinside.com 2019 - 2024. All rights reserved.