2012-11-07 45 views
1

下面的代碼是我創建的查詢的結果,除了一件事情之外,它都可以正常工作。我有材質ID的物料名稱:SQL帶回材質名稱

1 = bath 
2 = sink 
3 = toilet 

下面的作品,但顯示宿每種材料

Select cu.FName + ' ' + cu.SName as 'Name', 
cu.Address1 + ', ' + cu.Address2 + ', ' + cu.Address3 as 'Dispatch Address', 
cu.PostCode, 
co.DateOrdered, 
co.Material1, 
ma.MaterialName, 
co.material2, 
ma.MaterialName, 
ma.Price as 'Item Price' 
from Customers cu 
left join CustomerOrder co on co.CustomerID = cu.CustomerID 
left join ItemOrder it on it.OrderID = co.OrderID 
left join Materials ma on ma.MaterialID = co.Material1 
or co.material2 = ma.MaterialItemID or co.material3 = ma.MaterialItemID 

它顯示如下(只是材料列停止混亂)

Material1 | MaterialName | Material2 | Material2Name | Material3 | Material3Name 
    1   Sink   2   Sink   3    Sink 

任何人都可以幫忙嗎?

回答

2

有幾個方法可以做到這一點,包括使用materials表上多次JOIN得到結果:

Select cu.FName + ' ' + cu.SName as 'Name', 
    cu.Address1 + ', ' + cu.Address2 + ', ' + cu.Address3 as 'Dispatch Address', 
    cu.PostCode, 
    co.DateOrdered, 
    co.Material1, 
    ma1.MaterialName Material1Name, 
    co.material2, 
    ma2.MaterialName Material2Name, 
    ma1.Price as 'Item Price', 
    co.material3, 
    ma3.MaterialName Material3Name 
from Customers cu 
left join CustomerOrder co 
    on co.CustomerID = cu.CustomerID 
left join ItemOrder it 
    on it.OrderID = co.OrderID 
left join Materials ma1 
    on ma1.MaterialID = co.Material1 
left join Materials ma2 
    on co.material2 = ma2.MaterialItemID 
left join Materials ma3 
    on co.material3 = ma3.MaterialItemID 
+0

非常感謝你這有助於大的時間 – Annoscia

+0

一個問題,我會怎樣總結材料Id的值?而不是把ma1.price作爲'物品價格',我可以創建一個加起來一起價值3的價格線嗎? – Annoscia

+0

這聽起來像你可以使用(ma1.price + ma2.price + ma3.price)來獲得項目的總價格。 – Taryn