合并具有共同字段的两条记录并在 MySQL & PHP 中递增一个字段
Merging two records with a common field and increment one field in MySQL & PHP
我有一个table如下。我想避免的是在 table 中有两个产品 ID。如何使用查询合并两个公共字段并增加数量?
cartid | prodid | quanity |
1 | 9226582 | 3 |
2 | 9226582 | 5 |
3 | 7392588 | 1 |
想要的结果是 table 应该改变如下:
cartid | prodid | quanity |
1 | 9226582 | 8 |
3 | 7392588 | 1 |
我已经搜索过答案,但似乎都太复杂了。有没有一种简单的方法可以做到这一点?
使用 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
创建另一个具有相同架构的 table,
然后
insert into newtable
select min(cartid) cartid ,prodid,sum(quantity) quantity
from
yourtable
group by prodid
order by cartid
重命名新的table
如果你想更新数据库中的table,你可以这样做:
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
我有一个table如下。我想避免的是在 table 中有两个产品 ID。如何使用查询合并两个公共字段并增加数量?
cartid | prodid | quanity |
1 | 9226582 | 3 |
2 | 9226582 | 5 |
3 | 7392588 | 1 |
想要的结果是 table 应该改变如下:
cartid | prodid | quanity |
1 | 9226582 | 8 |
3 | 7392588 | 1 |
我已经搜索过答案,但似乎都太复杂了。有没有一种简单的方法可以做到这一点?
使用 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
创建另一个具有相同架构的 table, 然后
insert into newtable
select min(cartid) cartid ,prodid,sum(quantity) quantity
from
yourtable
group by prodid
order by cartid
重命名新的table
如果你想更新数据库中的table,你可以这样做:
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