1

下面的代码是我创建的查询的结果,除了一件事之外它都可以正常工作。我有材料名称的材料 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

有人可以帮忙吗?

4

1 回答 1

2

有几种方法可以做到这一点,包括JOINmaterials桌子上多次使用以获得结果:

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
于 2012-11-07T16:18:53.730 回答