LEFT JOIN与FOR XML AUTO,ELEMENTS

时间:2012-01-09 19:13:20

标签: sql-server xml

我有3张桌子

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

我想选择Master,Detail(作为Master中的SubElement),Item(在Detail的相同元素中)

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>'

我怎样才能以最佳实践方式做到这一点?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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')