2012-01-09 61 views
2

我有3個表LEFT JOIN與FOR XML AUTO,ELEMENTS

Master {MasterID, Desc}, 
Detail {MasterID, DetailID, ItemID}, 
Items {ItemID, ItemDesc}) 

我要選擇法師,詳細信息(如子元素在碩士),項目(詳情的相同元素)

SELECT Master.MasterID, Master.Desc, Detail.DetailID, Detail.ItemID, Items.ItemDesc 
FROM Master 
    LEFT JOIN Detail 
     LEFT JOIN Items 
      ON Detail.ItemID = Items.ItemID 
    ON Master.MasterID = Detail.MasterID 
FOR XML AUTO, ELEMENTS 

它給出以下結果:

<Master> 
<MasterID>1</MasterID> 
<Desc>Master1</Desc> 
<Detail> 
    <DetailID>1</DetailID> 
    <ItemID>1</ItemID> 
    <Items><ItemDesc>ItemDesc1</ItemDesc></Items> 
</Detail> 
</Master> 

但我的目標是

<Master> 
<MasterID>1</MasterID> 
<Desc>Master1</Desc> 
<Detail> 
    <DetailID>1</DetailID> 
    <ItemID>1</ItemID> 
    <ItemDesc>ItemDesc1</ItemDesc> 
</Detail> 
</Master>' 

我該如何以最佳實踐的方式做到這一點?

回答

3

製作細節和項目說明從單一查詢回來,就像這樣:

SELECT 
    Master.MasterID, 
    Master.Desc, 
    Detail.DetailID, 
    Detail.ItemID, 
    Detail.ItemDesc 
FROM 
    Master 
    LEFT JOIN (
     select 
      d.MasterID, 
      d.DetailID, 
      d.ItemID, 
      i.ItemDesc 
     from 
      Detail d 
      left join items i on 
       d.itemid = i.itemid 
    ) Detail ON 
     Master.MasterID = Detail.MasterID 
FOR XML AUTO, ELEMENTS 
0

您可以使用for xml path這樣。

select m.MasterID, 
     m.[Desc], 
     (select d.DetailID, 
       d.ItemID, 
       i.ItemDesc 
     from Detail as d 
      inner join Items as i 
      on d.ItemID = i.ItemID 
     where d.MasterID = m.MasterID 
     for xml path('Detail'), type) 
from Master as m 
for xml path('Master')