Home > Net >  SQL sum values from many to many
SQL sum values from many to many

Time:09-08

There's my sql data:

id  name  prod_id  price
------------------------
9    A     23      4100
94   B     40      1500
94   B     36      1500

I would ideally like to finally have:

id  name  prod_id  price
------------------------
9    A     23      4100
94   B     40,36   1500

Here's my code I've tried using GROUP BY

SELECT 
    company.id,
    company.name,
    order_product.product_id,
    SUM(orders.price)
FROM
    orders
INNER JOIN users ON orders.user_id = users.id
INNER JOIN order_product ON orders.id = order_product.order_id
INNER JOIN customer ON orders.customer_id = customer.id
INNER JOIN company ON customer.company_id = company.id
GROUP BY
company.id,

CodePudding user response:

group_concat should do the trick

SELECT 
    company.id,
    company.name,
    group_concat(order_product.product_id9,
    orders.price
FROM
    orders
INNER JOIN users ON orders.user_id = users.id
INNER JOIN order_product ON orders.id = order_product.order_id
INNER JOIN customer ON orders.customer_id = customer.id
INNER JOIN company ON customer.company_id = company.id
group by 
    company.id,
    company.name,
    orders.price
  • Related