SQL “select where not in subquery” returns no results

后端 未结 11 2007
滥情空心
滥情空心 2020-11-29 14:46

Disclaimer: I have figured out the problem (I think), but I wanted to add this issue to Stack Overflow since I couldn\'t (easily) find it anywhere. Also, someone might

11条回答
  •  生来不讨喜
    2020-11-29 15:43

    Let's suppose these values for common_id:

    Common - 1
    Table1 - 2
    Table2 - 3, null
    

    We want the row in Common to return, because it doesn't exist in any of the other tables. However, the null throws in a monkey wrench.

    With those values, the query is equivalent to:

    select *
    from Common
    where 1 not in (2)
    and 1 not in (3, null)
    

    That is equivalent to:

    select *
    from Common
    where not (1=2)
    and not (1=3 or 1=null)
    

    This is where the problem starts. When comparing with a null, the answer is unknown. So the query reduces to

    select *
    from Common
    where not (false)
    and not (false or unkown)
    

    false or unknown is unknown:

    select *
    from Common
    where true
    and not (unknown)
    

    true and not unkown is also unkown:

    select *
    from Common
    where unknown
    

    The where condition does not return records where the result is unkown, so we get no records back.

    One way to deal with this is to use the exists operator rather than in. Exists never returns unkown because it operates on rows rather than columns. (A row either exists or it doesn't; none of this null ambiguity at the row level!)

    select *
    from Common
    where not exists (select common_id from Table1 where common_id = Common.common_id)
    and not exists (select common_id from Table2 where common_id = Common.common_id)
    

提交回复
热议问题