SQL Server JOIN在两列不存在的情况下

时间:2017-08-04 11:16:30

标签: sql-server database sql-server-2008

我有

表1:

COLUMN1    COLUMN2   Column3  
----------------------------
Eva           Apple       15
Eva           cat         25
Eva           dog       35
Eva           shoe      45
Bob           Samsung     12
Bob           Samsung     12
Bob           NOKIA       75
...           ...        ...

表2:

COLUMN1    COLUMN2   Column3
----------------------------
Eva           Apple       45
Eva           cat         98
Eva           dog         7
Eva           shoe        3
Bob           Samsung     1

...           ...        ...

我想选择我加入两个表的地方,因为table1中不存在,其中join是在column2和column3上

SELECT  * [dbo].[table1]
FROM    
WHERE   NOT EXISTS
        (
        SELECT  [column2] , [column3]
        FROM    [dbo].[table2]
        WHERE  table1.column2 = table2.column2  and table1.column3 = table2.column3 
        )

我想得到这样的结果:

COLUMN1    COLUMN2   Column3  
----------------------------
Eva           Apple       45
Eva           cat         98
Eva           dog         7
Eva           shoe        3
Bob           Samsung     1
Bob           Samsung     5
Bob           NOKIA       75
...           ...         ...

感谢您提出解决此问题的意见

1 个答案:

答案 0 :(得分:0)

SELECT
    table1.column1,
    table1.column2,
    case 
        when table2.column3 is not null 
        then table2.column3
        else table1.column3
    end as column3

FROM
    table1
    left join table2
        on table1.column2 = table2.column2