我想通过将购物车中每件商品的价值相加来计算一个用户的购物车总产品。
我正在使用此查询:
SELECT *, SUM(quantity) OVER (PARTITION BY product_id ORDER BY id) AS TotalProducts
FROM cart WHERE user_id ='$user_id';
获取错误:
SQL语法;检查与MariaDB服务器对应的手册 在'(PARTITION BY product_id)附近使用正确语法的版本 ORDER BY id)
使用数据库架构进行编辑
id | product_id | quantity | user_id
1 | 37 | 2 | 23847
2 | 70 | 2 | 23847
我看不出我做错了什么?
答案 0 :(得分:2)
我不熟悉MariaDB语法,你没有展示你的架构,但这是我的回答:
SELECT c.*,
SUM(c.quantity) as `TotalProducts`
FROM cart c
WHERE c.user_id = '$user_id'
GROUP BY c.user_id
或者,如果您想要每件产品的总数,可以使用:
SELECT c.*,
SUM(c.quantity) as `TotalProducts`
FROM cart c
WHERE c.user_id = '$user_id'
GROUP BY c.user_id, c.product_id
答案 1 :(得分:1)
在MySQL中,您可以使用相关子查询:
SELECT c.*,
(SELECT SUM(c2.quantity)
FROM cart c2
WHERE c2.user_id = c.user_id AND
c2.product_id = c.product_id AND
c2.id <= c.id
) as TotalProducts
FROM cart c
WHERE user_id = '$user_id';