sql - MySQL SELECT x FROM a WHERE NOT IN (SELECT x FROM b) - 意外结果

标签 sql mysql

我希望下面第三个查询的结果包含 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 returns NULL not only if the expression on the left hand side is NULL, but also if no match is found in the list and one of the expressions in the list is NULL.

这正是你的情况。

INNOT 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/

相关文章:

php - Yii 为另一个模型中存在的字段创建 CButton 列

sql - SQL Server 中的 INSERT INTO SET 语法

sql - 将数组存储为字段值或将数组值存储为记录是个好主意吗?

mysql - 数据库错误 :migrate using JRuby on Rails with remote Amazon MySQL via SSL connection

php - 如何使用pdo准备语句在mysql中插入多条记录?

mysql - 在MySQL中计算风向的平均值

mysql - Linq2db(MySQL)。设置行索引

c# - 当 IDENTITY_INSERT 设置为 OFF 时,无法在表 'ClientDetails' 中为标识列插入显式值

MySQL 触发器导致错误 #1064

sql - Pl SQL 对 100 个 View 中的行进行计数,无需联合所有