我有一个表cart_items
,其中包含以下数据
+-----+---------+---------+------------+----------+
| id | user_id | cart_id | product_id | quantity |
+-----+---------+---------+------------+----------+
| 303 | 9 | 44 | 1 | 2 |
| 305 | 9 | 44 | 3 | 1 |
| 307 | 9 | 44 | 3 | 1 |
| 308 | 9 | 44 | 2 | 1 |
| 309 | 9 | 44 | 6 | 1 |
| 310 | 9 | 44 | 2 | 1 |
+-----+---------+---------+------------+----------+
我的问题是有重复的产品。我想要的桌子是这个
+-----+---------+---------+------------+----------+
| id | user_id | cart_id | product_id | quantity |
+-----+---------+---------+------------+----------+
| 303 | 9 | 44 | 1 | 2 |
| 305 | 9 | 44 | 3 | 2 |
| 308 | 9 | 44 | 2 | 2 |
| 309 | 9 | 44 | 6 | 1 |
+-----+---------+---------+------------+----------+
所以区别在于重复的product_id
被合并并增加了quantity
。
有没有一种简单的方法可以通过SQL查询做到这一点?
答案 0 :(得分:1)
您需要group by user_id, cart_id, product_id
并进行汇总:
select
min(id) id, user_id, cart_id, product_id, sum(quantity) quantity
from cart_items
group by user_id, cart_id, product_id