0

我需要有关如何编写 SQL Server 2005 查询来处理连接多个子表的帮助。这是我的场景:

表:

顾客

  • 客户_PK

订单

  • 订单_PK
  • 订单类型A_FK
  • 订单类型B_FK
  • 订单类型C_FK
  • 客户_FK

订单类型A

  • 订单类型A_PK
  • 托运人_FK

订单类型B

  • 订单类型B_PK
  • 托运人_FK

订单类型C

  • 订单类型C_PK
  • 托运人_FK

托运人

  • 托运人_PK
  • 发货人地址_FK

发货人地址

  • ShipperAddress_PK
  • 托运人州

Orders 表的数据如下所示:

Order_PK   OrdersTypeA_FK    OrdersTypeB_FK    OrdersTypeC_FK    Customer_FK
--------   --------------    --------------    --------------    -----------
1          1                 null              null              1
2          null              1                 null              2
3          null              null              1                 3

我的问题是我需要让 select join 语句通过从三个 OrdersType 表之一中查找 Shipper_FK 来检索 ShipperAddress。Orders 表每行只有一个 OrdersType FK。我需要从 OrdersType 表中检索的唯一内容是 Shipper_FK,以便我可以加入 ShipperAddress 表。

那么连接看起来如何???

select 
ShipperAddress.ShipperState 
from Customers
left join Orders on Orders.Customer_FK = Customers.Customer_PK

????????

left join Shippers on Shipper_PK = ??????.Shipper_FK
left join ShipperAddress on ShipperAddress.ShipperAddress_PK = Shippers.ShipperAddress_FK

我不能为每个 OrdersType 表单独连接到 ShipperAddress。这是一个较小的问题示例,在 OrdersType 级别有更多表。Shipper_FK 在每个 OrdersType 表中都是相同的。无论它来自哪个 OrdersType 表,我都需要访问 Shipper_FK 以继续执行 join 语句。怎么可能呢?

4

1 回答 1

1

这将是有趣的阅读,优化和维护......

SELECT sa.ShipperState  --, other columns surely
FROM dbo.Customers AS c
LEFT OUTER JOIN dbo.Orders AS o 
ON o.Customer_FK = c.Customer_PK
LEFT OUTER JOIN dbo.OrdersTypeA AS oa
  ON oa.OrdersTypeA_PK = o.OrdersTypeA_FK
LEFT OUTER JOIN dbo.OrdersTypeB AS ob
  ON ob.OrdersTypeB_PK = o.OrdersTypeB_FK
LEFT OUTER JOIN dbo.OrdersTypeC AS oc
  ON oc.OrdersTypeC_PK = o.OrdersTypeC_FK
LEFT OUTER JOIN dbo.Shippers AS s
  ON s.Shipper_PK = COALESCE(oa.Shipper_FK, ob.Shipper_FK, oc.Shipper_FK)
LEFT OUTER JOIN dbo.ShipperAddress AS sa
  ON s.ShipperAddress_FK = sa.ShipperAddress_PK;
于 2012-06-15T02:53:24.097 回答