SQL “Join” on null values

前端 未结 14 1284
旧巷少年郎
旧巷少年郎 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:38

    You can also use CASE to replace the null value in Subqueries, then JOIN the results:

    SELECT T1.COL1 FROM
    (
       (SELECT (CASE WHEN COL1 IS NULL THEN 'X' ELSE COL1 END) AS COL1 FROM TABLE1) T1
       JOIN
       (SELECT (CASE WHEN COL1 IS NULL THEN 'X' ELSE COL1 END) AS COL1 FROM TABLE2) T2
    )
    ON T1.COL1=T2.COL1
    
    0 讨论(0)
  • 2020-12-13 14:41

    Just throwing this out there -- is there a way you could coalesce those nulls into a known value, like an empty string? Not knowing much about how your table is laid out means that I can't be sure if you'll be losing meaning that way -- i.e. having an empty string represent "user refused to enter a phone number" and NULL being "we forgot to ask about it", or something like that?

    Odds are it's not possible, I'm sure, but if it is, you'll have known values to compare and you can get a legit join that way.

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

    For this sort of task Oracle internally uses an undocumented function sys_op_map_nonnull(), where your query would become:

    SELECT *
    FROM T1 JOIN T2 ON sys_op_map_nonnull(T1.SOMECOL) = sys_op_map_nonnull(T2.SOMECOL)
    

    Undocumented, so be careful if you go this route.

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

    In SQL Server I have used:

    WHERE (a.col = b.col OR COALESCE(a.col, b.col) IS NULL)
    

    Obviously not efficient, because of the OR, but unless there's a reserved value you can map NULLs to on both sides without ambiguity or folding that's about the best you can do (and if there was, why was NULL even allowed in your design...)

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

    Maybe this would work, but I've never actually tried it:

    SELECT * 
    FROM T1 JOIN T2 
    ON T1.SOMECOL = T2.SOMECOL OR (T1.SOMECOL IS NULL AND T2.SOMECOL IS NULL)
    
    0 讨论(0)
  • 2020-12-13 14:49

    You can join null values using decode:

        SELECT * FROM T1 JOIN T2 ON DECODE(T1.SOMECOL, T2.SOMECOL, 1, 0) = 1
    

    decode treats nulls as equal, so this works without "magic" numbers. The two columns must have the same data type.

    It won't make the most readable code, but probably still better than t1.id = t2.id or (t1.id is null and t2.id is null)

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