在SQL Server中加入2个表

时间:2022-02-08 09:31:57

I have 2 tables as following:

我有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

How to create the query as the following result:

如何创建查询,如下所示:

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

2 个解决方案

#1


2  

Try using 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


2  

This is what you need to do

这是你需要做的

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

#1


2  

Try using 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


2  

This is what you need to do

这是你需要做的

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