SQL带回材料名称

时间:2012-11-07 16:15:08

标签: sql sql-server-2008 tsql

下面的代码是我创建的查询的结果,除了一件事之外它都可以正常工作。我有材料名称的材质ID:

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

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

有几种方法可以做到这一点,包括多次在JOIN表上使用materials来获得结果:

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