MYSQL INNER JOIN AND GROUP BY

Amanda :

I have a product table that holds product details like name, price, img and etc, and orders table where records orders. On the orders table, I store the only product_id from products and I want to group my results. For example in my products table, I have

product_id, product_name, product_price
1           apple         10
2           juice         5
3           pineapple     7.5

As for my orders table for example, I have

order_id, product_id, quantity, date
1         1           3         20.02.2020
2         3           2         22.12.2019
3         3           4         12.12.2020
4         1           2         12.02.2020

I want to GROUP my ORDERS table by product name and quantity For example

product_name, quantity, price
apple         5         50
pineapple     6         45

And here is my query

SELECT 
products.product_id, 
products.product_name,
products.product_price AS price,
orders.quantity AS col,
orders.by_date,
(SELECT SUM(price * col)) AS total
FROM products
INNER JOIN orders ON products.product_id = orders.product_id
GROUP BY products.product_id,   
     products.product_name,
     orders.order_id

And the result is not as excepted

I'm not sure exactly what I'm doing wrong. Do I need to do a subquery?

Sithroo :
SELECT 
  p.product_name,
  SUM(o.quantity) AS quantity,
  SUM(o.quantity * p.product_price) AS price
FROM products p
INNER JOIN orders o
ON p.product_id = o.product_id
GROUP BY 
  p.product_name

The above should be sufficient to produce the result

roduct_name, quantity, price
apple         5         50
pineapple     6         45

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=238707&siteId=1