MYSQL Left Join how do I select NULL values?

后端 未结 4 1938
执念已碎
执念已碎 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)

    0 讨论(0)
  • 2020-12-09 15:21

    According to MySQL specification you should use "IS NULL" instead of "= NULL". It says that "(NULL = NULL) equals to NULL". But NULL equals False while it used as Boolean.

    0 讨论(0)
  • 2020-12-09 15:30

    To compare NULL values you have to use the IS NULL predicate, like this:

    SELECT table1.*, table2.*
    FROM table1
    LEFT JOIN table2 ON table1.id=table2.id
    WHERE table2.surname IS NULL
    
    0 讨论(0)
  • 2020-12-09 15:36

    try with:

    SELECT table1.*,table2.* 
    FROM table1 
      LEFT JOIN table2 ON table1.id=table2.id 
    WHERE table2.surname IS NULL
    
    0 讨论(0)
提交回复
热议问题