2014-04-01 90 views
5

我有2個表如下:加入SQL Server中2個表

TABLE_1

CODE1 CODE2  CODE3 SYNC 
    ----------------------------------- 
    02  03   04   YES 
    01  03   NULL   NO 
    01  02   03   NA 

TABLE_2

CODE  NAME 
    -------------- 
    01  ABC 
    02  BCD 
    03  DEF 
    04  EFG 

如何創建查詢的結果如下:

CODE1  CODE2  CODE3  SYNC 
    -------------------------------------- 
    BCD  DEF   EFG   YES 
    ABC  DEF   NULL  NO 
    ABC  BCD   DEF   NA 

回答

2

嘗試使用left join

SELECT 
    tblCODE1.NAME AS CODE1, 
    tblCODE2.NAME AS CODE2, 
    tblCODE3.NAME AS CODE3, 
    Table_1.SYNC 
FROM 
    Table_1 
    LEFT JOIN Table_2 as tblCODE1 
     ON tblCODE1.CODE=Table_1.CODE1 
    LEFT JOIN Table_2 as tblCODE2 
     ON tblCODE2.CODE=Table_1.CODE2 
    LEFT JOIN Table_2 as tblCODE3 
     ON tblCODE3.CODE=Table_1.CODE3 
2

這就是你需要做的

SELECT T2.CODE AS [CODE1],T3.CODE AS [CODE2],T4.CODE AS [CODE3],T.SYNC 
FROM Table_1 T 
LEFT JOIN Table_2 T2 ON T2.CODE = T.CODE1 
LEFT JOIN Table_2 T3 ON T3.CODE = T.CODE2 
LEFT JOIN Table_2 T4 ON T4.CODE = T.CODE3