ITPub博客

首页 > 数据库 > 数据库开发技术 > in null和not in null

in null和not in null

原创 数据库开发技术 作者:xuexiaogang 时间:2024-08-06 23:20:27 0 删除 编辑

这是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值。真的是非常正确的。


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/637517/viewspace-3024348/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论
OracleACE/PostgreSQLACE/阿里云MVP/腾讯云TVP/墨天轮 MVP/TiDBMVA/数盟会华东区长老/OpenTenBase社区委和技术委委员/架构师技术同盟名人堂成员上海地区理事会成员/if社区联合发起人/《DBA实战手记》作者/公众号:四海内皆兄弟

注册时间:2013-07-01

  • 博文量
    422
  • 访问量
    953269