I need help with how to write a SQL Server 2005 query to handle joining multiple subtables. Here is my scenario:
Tables:
Customers
- Customer_PK
Orders
- Order_PK
- OrdersTypeA_FK
- OrdersTypeB_FK
- OrdersTypeC_FK
- Customer_FK
OrdersTypeA
- OrdersTypeA_PK
- Shipper_FK
OrdersTypeB
- OrdersTypeB_PK
- Shipper_FK
OrdersTypeC
- OrdersTypeC_PK
- Shipper_FK
Shippers
- Shipper_PK
- ShipperAddress_FK
ShipperAddress
- ShipperAddress_PK
- ShipperState
The Orders table has data that looks like the following:
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
My issue is that I need to have the select join statement retrieve the ShipperAddress by finding the Shipper_FK from one of the three OrdersType tables. The Orders table will only have one of the OrdersType FK per row. The only thing I need to retreive from the OrdersType table is the Shipper_FK so that I can join to the ShipperAddress table.
So how does the join look???
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
I can’t have a separate join down to ShipperAddress for each of the OrdersType tables. This is a smaller sample of an issue that has many more tables at the OrdersType level. The Shipper_FK is the same in each of the OrdersType tables. I need to get at the Shipper_FK no matter what OrdersType table it came from to continue with the join statement. How can that be done?
This is going to be fun to read, optimize and maintain…