MySQL in,not in,exists,not exists与null的恩恩怨怨

这篇博客详细探讨了MySQL查询中null值如何影响'in', 'not in', 'exists' 和 'not exists' 的判断结果。总结了在这些条件表达式中,null值作为左比较符和右比较符时的不同行为,以及exists和not exists子查询对null的处理方式。" 440159,86004,PrePost:三维建模与流体计算软件,"['图形用户界面', '流体计算', '建模软件', 'C++', 'Windows平台']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

null这个东西在数据里算是个奇葩,在比较中也比较特殊,下面记录总结一下在in,not in,exists,not exists中null对判断结果的影响。
做一些描述声明,在比较符左边的我们称为左比较符,在比较符右边的我们称为右比较符,例如1 in (1,2),那么in左边的1是左比较符,in右边的(1,2)是右比较符。

1.in
1.1当左比较符是null,任何情况下都返回null。

mysql> select null in (1,2);
+---------------+
| null in (1,2) |
+---------------+
|          NULL |
+---------------+
1 row in set (0.00 sec)

mysql> select null in (1,2,null);
+--------------------+
| null in (1,2,null) |
+--------------------+
|               NULL |
+--------------------+
1 row in set (0.00 sec)

1.2当右比较符包含null,只当左比较符不为null,且右比较符包含左比较符时,返回1,其他情况均返回null。

mysql> select null in (1,2,null);
+--------------------+
| null in (1,2,null) |
+--------------------+
|               NULL |
+--------------------+
1 row in set (0.00 sec)

mysql> select 3 in (1,2,null);
+-----------------+
| 3 in (1,2,null) |
+-----------------+
|            NULL |
+-----------------+
1 row in set (0.00 sec)

mysql> select 1 in (1,2,null);
+-----------------+
| 1 in (1,2,null) |
+-----------------+
|               1 |
+-----------------+
1 row in set (0.00 sec)

2.not in
2.1当左比较符为null,任何情况都返回null。

mysql> select null not in (1,2,null);
+------------------------+
| null not in (1,2,null) |
+------------------------+
|                   NULL |
+------------------------+
1 row in set (0.00 sec)

mysql> select null not in (1,2);
+-------------------+
| null not in (1,2) |
+-------------------+
|              NULL |
+-------------------+
1 row in set (0.00 sec)

2.2当右比较符包含null,当右比较符包含左比较符时返回0,其他情况均返回null。

mysql> select 1 not in (1,2,null);
+---------------------+
| 1 not in (1,2,null) |
+---------------------+
|                   0 |
+---------------------+
1 row in set (0.00 sec)

mysql> select 1 not in (2,3,null);  
+---------------------+
| 1 not in (2,3,null) |
+---------------------+
|                NULL |
+---------------------+
1 row in set (0.00 sec)

3.exists
exists子查询返回null时判断为真。

mysql> select exists (select null);
+----------------------+
| exists (select null) |
+----------------------+
|                    1 |
+----------------------+
1 row in set (0.00 sec)

4.not exists
not exists子查询返回null时判断为假。

mysql> select not exists (select null);
+--------------------------+
| not exists (select null) |
+--------------------------+
|                        0 |
+--------------------------+
1 row in set (0.00 sec)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值