加入具有匹配值的行或加入null

时间:2018-03-14 16:32:03

标签: sql-server tsql

我想加入Column1和(如果有匹配则为Column2,如果没有则为null)

Table1
a,x
a,null
a,y

Table2
a,x,1
a,null,2

加入结果

a,x,1
a,null,2 
a,y,2

2 个答案:

答案 0 :(得分:0)

我想你想要这样的东西:

SELECT
    T.Column1,
    T.Column2,
    N.Column3
FROM
    Table1 AS T
    LEFT JOIN Table2 AS N ON 
        T.Column1 = N.Column1 AND
        ISNULL(T.Column2, 'someValueYouWillNeverFindInColumn2') = ISNULL(N.Column2, 'someValueYouWillNeverFindInColumn2')

答案 1 :(得分:0)

如果你的a,y将加入a,null,2,那么你的a,x也是如此,因此你最终会得到如下结果:

a,x,1
a,x,2
a,null,2 
a,y,2

我认为LEFT JOIN就是你想要的。类似的东西:

SELECT Table1.Column1, Table1.Column2, Table2.Column3
FROM 
Table1
LEFT JOIN
Table2
ON Table1.Column1 = Table2.Column1
AND ((Table1.Column2 = Table2.Column2) OR (Table2.Column2 is null))

这是完整的测试:

CREATE TABLE [dbo].[Table1](
    [Column1] [varchar](5) NULL,
    [Column2] [varchar](5) NULL,
)

CREATE TABLE [dbo].[Table2](
    [Column1] [varchar](5) NULL,
    [Column2] [varchar](5) NULL,
    [Column3] [varchar](5) NULL,
)

INSERT INTO Table1(Column1, Column2)
VALUES('a','x'), ('a',null), ('a','y')

INSERT INTO Table2(Column1, Column2, Column3)
VALUES('a','x', '1'), ('a',null, '2')

SELECT Table1.Column1, Table1.Column2, Table2.Column3
FROM 
Table1
LEFT JOIN
Table2
ON Table1.Column1 = Table2.Column1
AND ((Table1.Column2 = Table2.Column2) OR (Table2.Column2 is null))

SELECT * FROM Table1
SELECT * FROM Table2