SQL使用JOIN查询多个表 - Northwind

时间:2014-01-24 08:15:35

标签: mysql sql join union northwind

//个人理解,而不是新任务 所以在MS的示例db northwind中有表格:orders o,[order details] od,customers c

  • o有orderID,customerID(包含重复项)
  • od有orderID(包括重复),单价,数量,折扣
  • c有customerID,companyName

粗略地说, 我想加入

o.customerID = c.customerID; selecting companyName ///
          join on o.orderID = od.orderID; selecting unitprice, quantity, discount

我的最终目标是

 sum(q (up - d)) AS 'Order Total' group by od.orderID then
                  sum(Order Total) group by companyName(?)

我的主要问题是不知道如何正确加入或正确加入。

提前致谢

2 个答案:

答案 0 :(得分:1)

假设您根据需要创建了正确的Select语句,则连接部分应类似于:

从订单o在o.orderID = od.orderID上加入Order_Detail od    在o.customerID = c.customerID

上加入Customer c

联接类型可以是:joininner joinright/left join。这取决于你想要实现什么,即如果你想排除/包括空引用。但结构是一样的。

答案 1 :(得分:1)

SQL Fiddle

上查看您的方案
SELECT comp.`company_name` AS 'company',COUNT(DISTINCT o.id_sales_order) AS 'total_orders',SUM(`unit_price`) AS 'grand_total'
FROM sales_order AS o
LEFT JOIN sales_order_item AS od ON od.fk_sales_order = o.id_sales_order
LEFT JOIN customer AS c ON c.id_customer = o.fk_customer
LEFT JOIN company AS comp ON comp.id_company = c.fk_company_id
GROUP BY comp.`company_name`

希望这就是你要找的东西