简体   繁体   中英

How to get Mysql SUM of multiple columns in database

I want to calculate total products in cart for one user by summing values for each product in cart.

I'm using this query :

    SELECT *, SUM(quantity) OVER (PARTITION BY product_id ORDER BY id) AS TotalProducts 
    FROM cart WHERE user_id ='$user_id';

Getting error:

SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '(PARTITION BY product_id ORDER BY id)

EDIT with DB schema

id | product_id | quantity | user_id
1  | 37         | 2        | 23847
2  | 70         | 2        | 23847

I can't see what I'm doing wrong?

I'm not familiar with the MariaDB syntax, and you didn't show your schema, but here's my shot at an answer:

SELECT c.*,
    SUM(c.quantity) as `TotalProducts`
FROM cart c
WHERE c.user_id = '$user_id'
GROUP BY c.user_id

Or, if you want a total per product, you could use:

SELECT c.*,
    SUM(c.quantity) as `TotalProducts`
FROM cart c
WHERE c.user_id = '$user_id'
GROUP BY c.user_id, c.product_id

In MySQL, you can use a correlated subquery:

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';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM