如何创建子查询并在连接中使用它?

时间:2013-09-11 17:40:49

标签: sql sql-server-2008 tsql sql-server-2005

我想创建SQL查询,如下所示:

select *
from vwOrderRNI orni
left join vwOrderRN orn on orn.SysId in 
(
    select associatingid 
    from OrderRNAssociation 
    where AssociatedId = orni.SysId 
    and AssociationName = 'ORNItems'
)

left join vwPOrder po on po.SysId in 
(
    select AssociatingId 
    from PurchaseOAssociation 
    where AssociatedId = orn.SysId 
    and AssociationName = 'PO_OrderRequisitionNotes'
)

left join vwPOItem poi on poi.POrder = 
(
    -- above left join  i want to take po.SysId which is filter because of left join
)

如何在别名表中进行第二次左连接,以便我可以在第三个左连接中使用它?

2 个答案:

答案 0 :(得分:1)

我没有你的表来测试这个,但我认为这通常是你正在寻找的(为了清晰起见,增加了间距):

select *
from   vwOrderRNI orni

       left join (
           select AssociatingId, AssociatedId, AssociationName
           from   OrderRNAssociation
       ) as orna on orna.AssociatedId = orni.SysID and orna.AssociationName = 'ORNItems'

       left join vwOrderRN orn on orn.SysId = orna.AssociatingId

       left join (
             select AssociatingId , AssociatedId, AssociationName
             from   PurchaseOAssociation 
       ) as poa on orn.SysId = poa.AssociatedId and poa.AssociationName = 'PO_OrderRequisitionNotes'

       left join vwPOrder po on po.SysId = poa.AssociatingId

       left join vwPOItem poi on poi.POrder = poa.AssociatingId

我不确定我是否正确加入vwPOItem,因为您的评论表明您使用po.SysId加入,但您的问题建议您使用PurchaseOAssociation.AssociatingId。无论如何,您可以轻松地将其更改为您需要的内部联接子查询的别名。

答案 1 :(得分:1)

很难说不知道你的架构,但我认为你可以像这样简化你的查询,看起来你根本不需要这么大量的子查询:

select *
from vwOrderRNI as orni
    left outer join OrderRNAssociation as orna on
        orna.AssociatedId = orni.SysId and orna.AssociationName = 'ORNItems'
    left outer join vwOrderRN as orn on orn.SysId = orna.AssociatingId 
    left outer join PurchaseOAssociation as poa on
        poa.AssociatedId = orn.SysId and poa.AssociationName = 'PO_OrderRequisitionNotes'
    left outer join vwPOrder po as on po.SysId = poa.AssociatingId
    left join vwPOItem poi on poi.POrder = po.SysId