SQL “Join” on null values

前端 未结 14 1285
旧巷少年郎
旧巷少年郎 2020-12-13 14:04

For reasons beyond my control, I need to join two tables and I need null values to match. The best option I could think of was to spit out a UUID and use that as my comparis

相关标签:
14条回答
  • 2020-12-13 14:50

    Do you really want to be able to join the tables if a value is null? Can't you just exclude the possible null values in the join predicate? I find it hard to grok that rows in two tables can be related by a null value. If you have 100 nulls in table1.col_a and 100 nulls in table2.col_b, you're going to have 10000 rows returned just for the rows with null. It sounds incorrect.

    However, you did say you need it. Can I suggest coalescing the null column into a smaller string as character comparisons are relatively expensive. Even better, coalesce the nulls into an integer if the data in the columns is going to be text. Then you have very quick 'comparisons' and you're unlikely to collide with existing data.

    0 讨论(0)
  • 2020-12-13 14:50

    You could try using with the below query.

    SELECT *
    FROM TABLEA TA
    JOIN TABLEB TB ON NVL(TA.COL1,0)=NVL(TB.COL2,0);
    
    0 讨论(0)
  • 2020-12-13 14:50

    @Sarath Avanavu

    This one is not the best approach. If TA.COL1 keeps value 0 and TB.COL2 is NULL it will join those records, which is not correct.

    SELECT *
    FROM TABLEA TA
    JOIN TABLEB TB ON NVL(TA.COL1,0)=NVL(TB.COL2,0);
    
    0 讨论(0)
  • 2020-12-13 14:52

    I believe you could still could use nvl() for join:

    SELECT *
    FROM T1
    JOIN T2 ON NVL(T2.COL1,-1)=NVL(T1.COL1,-1);
    

    But you will need to add function based indexes on columns col1

    CREATE INDEX IND_1 ON T1 (NVL(COL1,-1));
    CREATE INDEX IND_2 ON T2 (NVL(COL1,-1));
    

    Indexes should improve the speed of the join on NVL(..) significantly.

    0 讨论(0)
  • 2020-12-13 14:54

    Simple, utilize COALESCE, which will return its first non-null parameter:

    SELECT * FROM T1 JOIN T2 ON 
      COALESCE(T1.Field, 'magic string') = 
         COALESCE(T2.Field, 'magic string')
    

    The only thing you will have to worry about is that 'magic string' cannot be among the legal values for the join field in either table.

    0 讨论(0)
  • 2020-12-13 14:56

    Isn't it the same as checking for presence of nulls in both columns?

    SELECT * FROM T1, T2 WHERE T1.SOMECOL IS NULL and T2.SOMECOL IS NULL
    

    or

    SELECT * FROM T1 CROSS JOIN T2 WHERE T1.SOMECOL IS NULL and T2.SOMECOL IS NULL
    
    0 讨论(0)
提交回复
热议问题