简体   繁体   中英

SQL Left Outer Join 2 Tables with 2 columns and different conditions for each column

I have a data table "DT" and a mapping table "MT" as follows:

DT table:

ComID - CountryCode
-------------------
1000    US
1001    US
1111    FR
1222    CN
1234    CN
1333    CN

MT table:

CountryCode - Region Name - ComID
----------------------------------
   US        North America   
   US            America    1001
   FR            Europe
   CN            CHINA      
   CN            ASIA       1222 
   CN            ASEAN      1333

I have a view which contains those 2 tables alongside with other mapping tables as well ( Data Table LEFT OUTER JOIN with other Mapping Tables )

What I want is to link the two table based on the country code, and for some exceptional companies I would like to use the ComID.

I have tried few queries but every one of them seems to not deliver the solution. Here is my try of achieving this:

    Select DT.*, MT.., ...    
    FROM   DT LEFT OUTER JOIN
           MT ON DT.CountryCode = MT.CountryCode AND DT .CC_COMPANY_CODE NOT IN ('1001', '1222', '1333') OR
    DT.ComID = MTComID AND DT.ComID IN ('1001', '1222', '1333')
    LEFT OUTER JOIN ... other tables ... LEFT OUTER JOIN ... other tables ...

The previous will return rows where both conditions applies:

CN -- CHINA -- 1234
CN -- ASIA -- 1222
CN -- ASEAN -- 1333

I have tried something like this but it will return a syntax error, the solution should be around this but I couldn't seem to find it.

Select DT.*, MT.., ...    
        FROM   DT LEFT OUTER JOIN
               MT ON DT.CountryCode = MT.CountryCode WHERE (DT .CC_COMPANY_CODE NOT IN ('1001', '1222', '1333')) OR
        ON DT.ComID = MTComID WHERE (DT.ComID IN ('1001', '1222', '1333'))
        LEFT OUTER JOIN ... other tables ...

This is one way to do it.

SELECT DT.CompID,DT.CountryCode,MT.RegionName
    FROM DT 
    JOIN MT 
        ON MT.CompID IS NOT NULL AND MT.CompID = DT.CompID
UNION
SELECT DT.CompID,DT.CountryCode,MT.RegionName
    FROM DT 
    JOIN MT 
        ON MT.CompID IS NULL AND MT.CountryCode = DT.CountryCode
        WHERE NOT EXISTS (SELECT TOP 1 1 FROM MT WHERE CompID = DT.CompID)

SQLFidder

Try not to hard-code the CompID as part of your logic as it will not be future proof.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM