SQL Server JOIN missing NULL values

前端 未结 8 1389
感情败类
感情败类 2020-12-04 15:15

Suppose I had the following 2 tables:

      Table1:                                Table2:
Col1:      Col2:     Col3:             Col1:       Col2:       Col         


        
相关标签:
8条回答
  • 2020-12-04 15:41

    Use Left Outer Join instead of Inner Join to include rows with NULLS.

    SELECT Table1.Col1, Table1.Col2, Table1.Col3, Table2.Col4
    FROM Table1 LEFT OUTER JOIN 
        Table2 ON Table1.Col1 = Table2.Col1 
        AND Table1.Col2 = Table2.Col2
    

    For more information, see here: http://technet.microsoft.com/en-us/library/ms190409(v=sql.105).aspx

    0 讨论(0)
  • 2020-12-04 15:42

    The only correct answer is not to join columns with null values. This can lead to unwanted behaviour very quickly.

    e.g. isnull(b.colId,''): What happens if you have empty strings in your data? The join maybe duplicate rows which I guess is not intended in this case.

    0 讨论(0)
  • 2020-12-04 15:45

    Try using ISNULL function:

    SELECT Table1.Col1, Table1.Col2, Table1.Col3, Table2.Col4
    FROM Table1 
    INNER JOIN Table2
       ON Table1.Col1 = Table2.Col1 
       AND ISNULL(Table1.Col2, 'ZZZZ') = ISNULL(Table2.Col2,'ZZZZ')
    

    Where 'ZZZZ' is some arbitrary value never in the table.

    0 讨论(0)
  • 2020-12-04 15:51

    Try using additional condition in join:

    SELECT Table1.Col1, Table1.Col2, Table1.Col3, Table2.Col4
    FROM Table1 
    INNER JOIN Table2
    ON (Table1.Col1 = Table2.Col1 
        OR (Table1.Col1 IS NULL AND Table2.Col1 IS NULL)
       )
    
    0 讨论(0)
  • 2020-12-04 15:56

    for some reason I couldn't get it to work with the outer join.

    So I used:

    SELECT * from t1 where not Id in (SELECT DISTINCT t2.id from t2)
    
    0 讨论(0)
  • 2020-12-04 15:57

    Dirty and quick hack:

    SELECT Table1.Col1, Table1.Col2, Table1.Col3, Table2.Col4
    FROM Table1 INNER JOIN Table2 ON Table1.Col1 = Table2.Col1
     AND ((Table1.Col2 = Table2.Col2) OR (Table1.Col2 IS NULL AND Table2.Col2 IS NULL))
    
    0 讨论(0)
提交回复
热议问题