我有一张table如下。我想避免的是表中有两个产品id。如何使用查询合并两个公共字段并增加数量?
cartid | prodid | quanity | 1 | 9226582 | 3 | 2 | 9226582 | 5 | 3 | 7392588 | 1 |
cartid | prodid | quanity |
1 | 9226582 | 3 |
2 | 9226582 | 5 |
3 | 7392588 | 1 |
预期结果是,该表应修改如下:
cartid | prodid | quanity | 1 | 9226582 | 8 | 3 | 7392588 | 1 |
1 | 9226582 | 8 |
我一直在寻找答案,但似乎都太复杂了。有没有一种简单的方法可以做到这一点?
enxuqcxy1#
如果要更新数据库中的表,可以执行以下操作:
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
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 quantity1 9226582 83 7392588 1
cartid prodid quantity
1 9226582 8
3 7392588 1
如果你对结果满意,你可以
drop table yourtablealter table newtable rename to yourtable
drop table yourtable
alter table newtable rename to yourtable
jexiocij2#
使用group by和min-看看这个-http://sqlfiddle.com/#!9/6c4332/4号
select min(cartid) cartid ,prodid,sum(quantity) quantityfrom yourtablegroup by prodidorder by cartid
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
重命名newtable
2条答案
按热度按时间enxuqcxy1#
如果要更新数据库中的表,可以执行以下操作:
输出:
如果你对结果满意,你可以
jexiocij2#
使用group by和min-
看看这个-http://sqlfiddle.com/#!9/6c4332/4号
创建另一个具有相同架构的表,然后
重命名newtable