合并具有相同id的sql行,求和并更新总数

时间:2009-10-28 20:33:53

标签: php mysql

我正在尝试编写一个php脚本来比较数据库中的行,然后添加产品ID匹配的数量。基于cusotmer_id

示例:

mydb.cart

id, customer_id, cart_id, product_id, qty, price

1, 0001000, 4545453, 20, 10, 12.99
2, 0001000, 7473432, 20, 2, 12.99

Result
3, 0001000, 7473432, 20, 12, 25.98

尝试合并上一个会话中的购物车信息。

感谢任何建议,

由于

2 个答案:

答案 0 :(得分:1)

您可以在SQL中而不是在PHP中执行此操作。更新新购物车行并删除旧购物车行。不确定这是否是正确的MySQL语法,但它应该类似于以下内容:

UPDATE cart SET qty = (
    SELECT SUM(qty) FROM cart c WHERE c.id = id 
    GROUP BY c.customer_id, c.product_id)
  WHERE EXISTS (
    SELECT 'x' FROM cart c2 
    WHERE c1.customer_id = c2.customer_id
    AND c1.product_id = c2.product_id
    AND c1.id < id);

DELETE FROM cart c1 WHERE EXISTS (
    SELECT 'x' FROM cart c2 
    WHERE c1.customer_id = c2.customer_id
    AND c1.product_id = c2.product_id
    AND c1.id < id);

答案 1 :(得分:0)

select sum(id)
     , customer_id
     , cart_id
     , product_id
     , sum(qty)
     , sum(price)
  from mydb.cart
group
    by customer_id
     , cart_id
     , product_id