SQL QUERY多个表Newby

时间:2014-11-19 19:43:13

标签: mysql sql-server

我是SQL的新手,我正在尝试完成以下任务: 我需要创建一个查询,该查询将根据一组日期返回一组结果。这是我的TABLES /列:

订单行

order_id,
line_no,
qty_shipped,
total_shipped_qty,
part_id,
part_description,
desired_ship_date,
ship_date,
customer_id

托运人

packlist,
order_id

客户

name,
customer_id

客户订单

PO, 
order_id

我需要输出看起来像这样:

packlist,
order_id,
line_no,
total_shipped_qty,
part_id, 
part_description,
name,
po,
desired_ship_date,
ship_date,

到目前为止,我已经提出了一个查询,根据一组日期从订单行表中获取我需要的所有列数据。我在连接其他表时遇到问题,无法在输出中获得我需要的其余列。特别是他们的表中的packlist,po和name。我需要先运行此查询:

SELECT ORDER_ID,
       LINE_NO,
       TOTAL_SHIPPED_QTY,
       PART_DESCRIPTION,
       DESIRED_SHIP_DATE,
       SHIP_DATE,
       TOTAL_SHIPPED_QTY
FROM   ORDER_LINE
WHERE  [SHIP_DATE] BETWEEN 'XXXX/XX/XX' AND 'XXXX/XX/XX' 

基于上面的结果,我需要从其他表中提取其余数据。任何帮助是极大的赞赏。谢谢

2 个答案:

答案 0 :(得分:1)

SELECT s.packlist, o.Order_ID, 
o.total_shipped_qty,o.Part_ID, o.Part_Description, co.PO,
c.Name, o.Desired_Ship_Date, o.Ship_Date 
from OrderLine o 
inner join Customers c on c.Customer_ID = o.Customer_ID 
inner join Shipper s on s.Order_ID = o.Order_ID
inner join CustomerOrders co on co.Order_ID = o.Order_ID
WHERE  o.[SHIP_DATE] BETWEEN 'XXXX/XX/XX' AND 'XXXX/XX/XX' 

此时我认为您不需要加入CustomerOrders。

答案 1 :(得分:0)

所有表格中只有INNER JOIN是您需要的

SELECT S.PACKLIST,
       O.ORDER_ID,
       O.TOTAL_SHIPPED_QTY,
       O.PART_ID,
       O.PART_DESCRIPTION,
       C.NAME,
       CO.PO,
       O.DESIRED_SHIP_DATE,
       O.SHIP_DATE
FROM   ORDERLINE O
       JOIN CUSTOMERS C
         ON C.CUSTOMER_ID = O.CUSTOMER_ID
       JOIN SHIPPER S
         ON S.ORDER_ID = O.ORDER_ID
       JOIN CUSTOMERORDER CO
         ON CO.ORDER_ID = O.ORDER_ID
WHERE  O.[SHIP_DATE] BETWEEN 'XXXX/XX/XX' AND 'XXXX/XX/XX'