简体   繁体   中英

Mysql: where ..id != X doesn't include the NULL foreign key

I have this Mysql table:

assignment: assignment_id (PK), company_id (FK), ...some other fields...

The FK company_id can be NULL if an assignment is not yet assigned to a company.

Now, I want to query all assignments that are not for company with id 2. So I did:

SELECT * FROM assignment WHERE company_id != 2

To my surprise, assignments with company_id NULL aren't returned in the results. I'd say that NULL != 2 so it should be returned. It works fine if I go with

(company_id IS NULL OR company_id != 2)

Can someone explain me the logic behind this? Does it have to do with the FK constraint?

The logic is simple: you can't really say whether or not NULL is equal to 2, because you don't know anything about NULL . Quoting the doc :

Conceptually, NULL means “a missing unknown value” and it is treated somewhat differently from other values. You cannot use arithmetic comparison operators such as =, <, or <> to test for NULL . [...] Because the result of any arithmetic comparison with NULL is also NULL , you cannot obtain any meaningful results from such comparisons.

You've already shown one possible workaround in your question, the other one is using <=> ( NULL-safe comparison operator ):

SELECT * FROM assignment
WHERE NOT(company_id <=> 2)

NULL is not a number. It is a completely different thing in mysql. So you can not compare something to NULL. To clear your confusion, in your case, all the fields where FK is not 2 are those fields where the "value" is other than 2. But when the value is NULL, it means there is no value assigned at all.

See MySql documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM