如何从mysql中的三个表中选择和计数数据

时间:2019-10-03 06:59:17

标签: mysql rdbms

我有三个桌子

1 - Products 
2- Orders
3- Order_item 

表(产品)

ID | Product_name | 
--------------------
1  | Samsung Galaxy 

表格(订单)

ID | Client_name 
-------------------
1  | Admin

表(Orders_item)

ID | Order_ID | Product_ID | Quantity 
-------------------------------------
1  | 1        | 1          | 1

2  | 1        | 1          | 1 

3  | 1        | 1          | 1 

我想在订单为1时选择产品名称,客户名称和数量。我已经尝试过此查询

SELECT products.name,orders.order_id,orders.client_name,order_item.quantity COUNT(*) FROM products,orders,order_item WHERE products.id = order_item.product_id AND orders.order_id = order_item.order_id AND orders.order_id=1 

返回的结果类似

Name | Order_ID | Client_name | Quantity 
----------------------------------------
Sa..| 1         | Admin       | 1 
Sa..| 1         | Admin       | 1 
Sa..| 1         | Admin       | 1

我想得到

这样的结果
Samsung | 1 | Admin | 3 

请帮助我。

1 个答案:

答案 0 :(得分:1)

您需要一个GROUP BY

SELECT products.Product_name AS Name,
       orders.id AS Order_ID,
       orders.client_name AS Client_name,
       SUM(order_item.Quantity) AS Quantity
FROM products
LEFT JOIN order_item 
ON order_item.Product_ID = products.ID
LEFT JOIN orders
ON orders.ID = order_item.Order_ID
WHERE orders.id=1
GROUP BY products.Product_name,
         orders.id,
         orders.client_name

这将输出:

| Name           | Order_ID | Client_name | Quantity |
| -------------- | -------- | ----------- | -------- |
| Samsung Galaxy | 1        | Admin       | 3        |

请注意,JOIN也可能是一本好书。