-1

我想按如下方式创建 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
)

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

4

2 回答 2

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
于 2013-09-11T18:11:38.210 回答
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是否正确加入,因为您的评论建议您加入 using po.SysId,但您的问题建议您使用PurchaseOAssociation.AssociatingId. 无论如何,您现在可以轻松地将其更改为您需要的内容,因为内部连接的子查询是别名的。

于 2013-09-11T18:09:25.830 回答