Merging two records with a common field and increment one field in MySQL & PHP

28 Views Asked by At

I have a table as follows. What I would like to avoid is having two product id's in the table. How can I merge the two common fields using a query and increment the quantity?

cartid |  prodid     | quanity |

   1   |  9226582    | 3       |

   2   |  9226582    | 5       | 

   3   |  7392588    | 1       |

The desired results is that the table should be altered as follows:

cartid |  prodid    | quanity |

   1   |  9226582   | 8       |

   3   | 7392588    | 1       |

I have searched for answers but all seem too complex. Is there a way to do this in a simple way?

2

There are 2 best solutions below

0
Nick On BEST ANSWER

If you want to update the table in the database, you can do this:

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

Output:

cartid  prodid      quantity
1       9226582     8
3       7392588     1

If you're happy with the result you can then

drop table yourtable
alter table newtable rename to yourtable
1
Kedar Limaye On

Use group by and min-

check this-http://sqlfiddle.com/#!9/6c4332/4

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

create another table with same schema, then

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

Rename the newtable