简体   繁体   English

MYSQL 内部联接和分组依据

[英]MYSQL INNER JOIN AND GROUP BY

I have a product table that holds product details like name, price, img and etc, and orders table where records orders.我有一个产品表,其中包含名称、价格、img 等产品详细信息,以及记录订单的订单表。 On the orders table, I store the only product_id from products and I want to group my results.在订单表上,我存储产品中唯一的 product_id 并且我想对我的结果进行分组。 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我想按产品名称和数量对我的 ORDERS 表进行分组 例如

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?我需要做一个子查询吗?

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

First aggregate in the table orders and then join to products:首先聚合表中的orders ,然后加入产品:

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

See the demo.请参阅演示。
Results:结果:

| product_id | product_name | quantity | price |
| ---------- | ------------ | -------- | ----- |
| 1          | apple        | 5        | 50    |
| 3          | pineapple    | 6        | 45    |

No subquery needed...不需要子查询...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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