从内部加入中正确加入

时间:2014-05-08 19:28:22

标签: join inner-join right-join

我有一个查询三个临时表。

  1. 表1当PC = 6而不是7
  2. 时返回PID
  3. 表2当PC = 1而不是7
  4. 时返回PID
  5. 表3返回PID而不是7
  6. 前两个临时表具有完美的内部连接,并且仅返回PC = 6且PC = 1的PID,但是当它等于7时则不返回。

    但是,我想要的是第三部分,在PC上进行右外连接,并返回包含PC = 6或PC = 1且不在内连接中的所有PID。相反,右外连接返回相同的值。有人可以帮我一把吗?

     --CREATE TEMP TABLE TO PULL PIDs w PLCs but no True Owner--
    SELECT 
    Distinct P.PropertyID as PID
    ,PC.LocationID AS PLC
    
    INTO #TempPLC
    
    FROM  
    Property AS P
    left join
    PropertyContact As PC on PC.PropertyID = P.PropertyID
    
    
    WHERE
        P.PropertyID=PC.PropertyID
        and 
        PC.ContactRoleID = 6 
        and not exists 
        (select 1 
        from 
        Enterprise.dbo.PropertyContact 
        where 
        PropertyID=P.PropertyID 
        and 
        ContactRoleID=7) 
    
    
    
    
    --CREATE TEMP TABLE TO PULL PIDs w Recorded but no True Owner--
    USE ENTERPRISE--    
    
    SELECT 
    Distinct P.PropertyID as PID
    ,PC.LocationID AS Recorded
    
    INTO #TempRecorded
    FROM 
    Property AS P
    left join
    PropertyContact As PC on PC.PropertyID = P.PropertyID
    
    WHERE
        P.PropertyID=PC.PropertyID
        and
        PC.ContactRoleID = 3 
        (select 1 
        from 
        Enterprise.dbo.PropertyContact 
        where 
        PropertyID=P.PropertyID 
        and 
        ContactRoleID=7) 
    
    
    --CREATE TEMP TABLE TO PULL PIDs w PLCs but no True Owner--
    
    SELECT 
    P.PropertyID as PID
    ,PC.LocationID AS RemainingLocs
    
    
    INTO #TempRemaining
    FROM
    Property AS P
    left join
    PropertyContact As PC on PC.PropertyID = P.PropertyID
    
    WHERE
        P.PropertyID=PC.PropertyID
        and not exists 
        (select 1 
        from 
        Enterprise.dbo.PropertyContact 
        where 
        PropertyID=P.PropertyID 
        and 
        ContactRoleID=7)    
    
    --RETURN RESULTS OF ALL PIDS w. BOTH RECORDED AND TRUE OWNERS--
    SELECT
    
    Distinct #TempRemaining.PID
    ,#TempRemaining.RemainingLocs
    ,#TempRecorded.Recorded
    
    FROM
    #TempPLC
    inner join
    #TempRecorded on #TempRecorded.PID = #TempPLC.PID
    right join
    #TempRemaining on #TempRecorded.Recorded = #TempRemaining.RemainingLocs
    
    
    WHERE
    #TempRecorded.Recorded = #TempPLC.PLC
    
    --DROP TEMP TABLES--
    drop table #TempPLC
    drop table #TempRecorded
    drop table #TempRemaining
    

0 个答案:

没有答案