【问题标题】:Merging two records with a common field and increment one field in MySQL & PHP在 MySQL 和 PHP 中将两条记录与一个公共字段合并并增加一个字段
【发布时间】:2018-10-20 06:18:41
【问题描述】:

我有一张如下表。我想避免的是在表中有两个产品 ID。如何使用查询合并两个常用字段并增加数量?

cartid |  prodid     | quanity |

   1   |  9226582    | 3       |

   2   |  9226582    | 5       | 

   3   |  7392588    | 1       |

期望的结果是该表应更改如下:

cartid |  prodid    | quanity |

   1   |  9226582   | 8       |

   3   | 7392588    | 1       |

我已经寻找答案,但似乎都太复杂了。有没有办法以简单的方式做到这一点?

【问题讨论】:

    标签: mysql merge increment records


    【解决方案1】:

    如果要更新数据库中的表,可以这样做:

    create table newtable
       (`cartid` int, `prodid` int unique key, `quantity` int);
    
    insert into newtable
       select * from yourtable order by cartid
       on duplicate key update quantity=newtable.quantity+values(quantity)
    
    select * from newtable
    

    输出:

    cartid  prodid      quantity
    1       9226582     8
    3       7392588     1
    

    如果你对结果感到满意,那么你可以

    drop table yourtable
    alter table newtable rename to yourtable
    

    【讨论】:

      【解决方案2】:

      使用 group by 和 min-

      检查这个-http://sqlfiddle.com/#!9/6c4332/4

      select min(cartid) cartid ,prodid,sum(quantity) quantity
      from 
      yourtable
      group by prodid
      order by cartid
      

      创建另一个具有相同架构的表, 那么

      insert into newtable 
      select min(cartid) cartid ,prodid,sum(quantity) quantity
          from 
          yourtable
          group by prodid
          order by cartid
      

      重命名新表

      【讨论】:

      • 谢谢。我希望表在数据库中实际更新。我该怎么做
      猜你喜欢
      • 2019-11-29
      • 1970-01-01
      • 2015-05-14
      • 1970-01-01
      • 2013-05-07
      • 1970-01-01
      • 1970-01-01
      • 2010-11-14
      • 1970-01-01
      相关资源
      最近更新 更多