暂无图片
暂无图片
1
暂无图片
暂无图片
暂无图片

in null和not in null

原创 薛晓刚 2024-08-06
106

这是A和X两个表的样本数据

mysql> select * from x;
±-----±-----±-----+
| id | a | c |
±-----±-----±-----+
| 1 | 1 | 1 |
| 2 | 2 | 2 |
| 3 | 3 | 3 |
| 4 | 4 | 4 |
| 5 | 5 | 5 |
| 6 | 6 | 6 |
| 7 | 7 | 7 |
| 8 | 8 | 8 |
| 9 | 9 | 9 |
| 10 | 10 | 10 |
±-----±-----±-----+
10 rows in set (0.01 sec)

mysql> select * from a;
±-----±-----±-----------±-----±-----------+
| id | name | time | flag | randchar |
±-----±-----±-----------±-----±-----------+
| 1 | 1 | 2020-10-01 | a | fd5e5045-4 |
| 2 | 2 | 2021-10-01 | A | fd5e5e80-4 |
| 3 | NULL | 2022-10-01 | a | fd5e639a-4 |
| 4 | 4 | 2023-01-01 | aB | fd5e67b4-4 |
| 4 | 4 | 2024-01-01 | aB | fd5e6ae9-4 |
| 2 | 10 | 2025-05-01 | A | fd5e6e82-4 |
| 5 | f | 2023-01-01 | h | sad3qwe |
| 5 | E | 2024-07-21 | f | asdasad |
| 6 | g | 2024-07-21 | g | asfdgfgad |
| 7 | h | 2024-07-21 | k | dsfcvcxssd |
| 8 | t | 2024-07-21 | NULL | asdasad |
| 9 | r | NULL | NULL | NULL |
| 10 | p | 2024-07-23 | F | NULL |
| 11 | p | 2024-07-23 | NULL | NULL |
| 1 | 3 | NULL | NULL | NULL |
±-----±-----±-----------±-----±-----------+
15 rows in set (0.01 sec)

分割
++++++++++++++++++++++++++++++++

下面是一种常见的写法。

mysql> select * from x where a in (1);
±-----±-----±-----+
| id | a | c |
±-----±-----±-----+
| 1 | 1 | 1 |
±-----±-----±-----+
1 row in set (0.00 sec)

而下面这种写法不常见,甚至是罕见。

mysql> select * from x where a in (1,null);
±-----±-----±-----+
| id | a | c |
±-----±-----±-----+
| 1 | 1 | 1 |
±-----±-----±-----+
1 row in set (0.00 sec)

下面是重点。not in的写法很正常。
mysql> select * from x where a not in (1);
±-----±-----±-----+
| id | a | c |
±-----±-----±-----+
| 2 | 2 | 2 |
| 3 | 3 | 3 |
| 4 | 4 | 4 |
| 5 | 5 | 5 |
| 6 | 6 | 6 |
| 7 | 7 | 7 |
| 8 | 8 | 8 |
| 9 | 9 | 9 |
| 10 | 10 | 10 |
±-----±-----±-----+
9 rows in set (0.00 sec)

但是这个结果有点让我没想到。而这都是OCP的考试内容。不过还是我的盲点。可能有人会说不会这样写的。但是如果括号内是子查询呢

mysql> select * from x where a not in (1,null);
Empty set (0.00 sec)

所以我做一个推断。这里id小于4的子查询中的name有null值

mysql> select * from x where x.a in (select name from a where id<=4);
±-----±-----±-----+
| id | a | c |
±-----±-----±-----+
| 1 | 1 | 1 |
| 3 | 3 | 3 |
| 2 | 2 | 2 |
| 10 | 10 | 10 |
| 4 | 4 | 4 |
±-----±-----±-----+
5 rows in set (0.02 sec)

mysql> select * from x where x.a not in (select name from a where id<=4);
Empty set (0.01 sec)

结果就是空的。

也许也有人和我一样因为盲点没想到。但是这就造成了逻辑判断的失误。

所以我一再要求参与业务运算和判断的字段不要有null值。真的是非常正确的。

「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论