【问题标题】:Mysql returns no values when null values are present In the subquery子查询中存在空值时Mysql不返回值
【发布时间】:2016-10-12 08:41:20
【问题描述】:

我确实有两个表 table1table2。其内容如下

mysql> select id from table1;
+------+
| id   |
+------+
|    1 |
|    2 |
|    3 |
|    4 |
+------+
4 rows in set (0.00 sec)

mysql> select id from table2;
+------+
| id   |
+------+
|  301 |
|    2 |
| NULL |
+------+
3 rows in set (0.00 sec)

当我在 mysql 控制台中点击以下查询时,它总是返回空集

select id 
from table1 
where id 
not in (select id from table2);

空集(0.00 秒)

当子查询中有空值时 innot in 是否会出现故障......?

我已经通过使用以下查询解决了它

select id 
from table1 
where id 
not in (select id from table2 where id is not null);
+------+
| id   |
+------+
|    1 |
|    3 |
|    4 |
+------+

3 行(0.00 秒)

只想知道

提前致谢:)

编辑:This question 试图清除一些空气,但还不够

【问题讨论】:

标签: php mysql sql


【解决方案1】:

not in 就是这样工作的。我建议您改用not exists

select id 
from table1 t1
where not exists (select 1 from table2 t2 where t1.id = t2.id);

为什么not in 会这样工作?这是因为not in 的语义。请记住,SQL 中的NULL(通常)表示 unknown 值。因此,如果您有一个“(1, 2)”列表,您可以说“3”不在列表中。如果你有 "(1, 2, unknown)" 你不能这么说。相反,结果是NULL,它被视为假。

NOT EXISTS 不这样,所以我觉得用起来更方便。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-17
    • 2022-11-20
    • 2015-06-17
    • 1970-01-01
    • 2018-04-11
    相关资源
    最近更新 更多