我希望下面第三个查询的结果包含 id=732。它没有。这是为什么呢?
mysql> SELECT id FROM match ORDER BY id DESC LIMIT 5 ; +------------+ | id | +------------+ | 732 | | 730 | | 655 | | 458 | | 456 | +------------+ 5 rows in set (0.00 sec) mysql> SELECT id FROM email ORDER BY id DESC LIMIT 5 ; +------------+ | id | +------------+ | 731 | | 727 | | 725 | | 724 | | 723 | +------------+ 5 rows in set (0.00 sec) mysql> SELECT * FROM match WHERE id NOT IN ( SELECT id FROM email ) ; Empty set (0.00 sec)
email.id 表中有 3 个 NULL 条目,match.id 中没有 NULL 条目。
完整的表/查询可以在 http://pastebin.ca/1462094 看到
最佳答案
来自 documentation :
To comply with the
SQL
standard,IN
returnsNULL
not only if the expression on the left hand side isNULL
, but also if no match is found in the list and one of the expressions in the list isNULL
.
这正是你的情况。
IN
和 NOT IN
都返回 NULL
,这不是 WHERE
子句可接受的条件。
按如下方式重写您的查询:
SELECT *
FROM match m
WHERE NOT EXISTS
(
SELECT 1
FROM email e
WHERE e.id = m.id
)
关于sql - MySQL SELECT x FROM a WHERE NOT IN (SELECT x FROM b) - 意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1001144/