MYSQL Left Join how do I select NULL values?

后端 未结 4 1939
执念已碎
执念已碎 2020-12-09 14:43

This is a follow up question to my last question about table joins in MySQL

I need to be able to select the NULL values from the left joined table.

Here\'s m

4条回答
  •  死守一世寂寞
    2020-12-09 15:21

    You have to use IS NULL instead of = NULL:

    WHERE table2.surname IS NULL
    

    The reason why you can't simply do = NULL is because NULL is essentially an "unknown" and can't equal or not equal to anything (not even itself), so trying to compare it to something as if it were supposed to be an exact match would simply return NULL instead of an expected boolean 0 or 1, and that's exactly why your query was returning an empty result.

    There's a clear difference between "is unknown" and "equals unknown". You can surely test if something is unknown or is not unknown, but you can't test if something "equals" unknown because unknown is unknown, and it wouldn't make sense.

    Also, since you're using MySQL, another option would be to use table2.surname <=> NULL, where <=> is a MySQL-specific NULL-Safe comparison operator, but try not to use that and just stick with the standard SQL way (IS NULL / IS NOT NULL)

提交回复
热议问题