代码之家  ›  专栏  ›  技术社区  ›  np.

从另一个表更新表中的数据

  •  0
  • np.  · 技术社区  · 3 年前

    我有两张桌子:
    cart_item

    id, session_id, product_id, quantity
    1   1           2           5
    2   1           3           5
    

    product

    id, quantity
    2   50
    3   75
    

    如何正确更新数据库中的数据 产品 表中的数据为基础 购物车 桌子我想更新表中产品的数量 产品 .
    通过更新 产品 我将删除表中的所有产品 购物车 . 以下是我在更新数据时希望得到的信息:
    产品

    id, quantity
    2   45
    3   70
    
    2 回复  |  直到 3 年前
        1
  •  1
  •   D-Shih    3 年前

    你可以尝试使用 UPDATE ... JOIN 来计算这个值。

    UPDATE product p 
    JOIN cart_item ci ON ci.product_id = p.id
    SET p.quantity = p.quantity - ci.quantity
    

    sqfliddle

        2
  •  0
  •   DhruvJoshi    3 年前

    也许是下面这样的问题

    update p
    set p.quantity = p.quantity - sum(ci.quantity)
    from product p
    join cart_item ci
    on ci.product_id=p.id
    group by p.id