SQL Server JOIN missing NULL values

前端 未结 8 1459
感情败类
感情败类 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:57

    you can just map like that

    select * from tableA a
    join tableB b on isnull(a.colID,'') = isnull(b.colId,'')
    
    0 讨论(0)
  • 2020-12-04 15:58

    You can be explicit about the joins:

    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) AND
             (Table1.Col2 = Table2.Col2 or Table1.Col2 is NULL and Table2.Col2 is NULL)
    

    In practice, I would be more likely to use coalesce() in the join condition:

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

    Where '' would be a value not in either of the tables.

    Just a word of caution. In most databases, using any of these constructs prevents the use of indexes.

    0 讨论(0)
提交回复
热议问题