解决mysql使⽤notin包含null值的问题
注意
select * from user where uid not in (a,b,c,null);
这个sql不回返回任何结果。要避免not in的list中出现null的情况。
另外:
–如果null参与算术运算,则该算术表达式的值为null。(例如:+,-,*,/ 加减乘除)
–如果null参与⽐较运算,则结果可视为false。(例如:>=,<=,<> ⼤于,⼩于,不等于)
–如果null参与聚集运算,则聚集函数都置为null(使⽤isnull(字段,0)等⽅式可以避免这种情况)。除count(*), count(1),
count(0)等之外(count(字段) 字段为null的⾏不参与计数)。
--如果在not in⼦查询中有null值的时候,则不会返回数据。
补充:MySQL in,not in,exists,not exists与null的恩恩怨怨
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)
< 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)
exists⼦查询返回null时判断为真。
mysql> select exists (select null);
+----------------------+
| exists (select null) |
+----------------------+
|    1 |
+----------------------+
1 row in set (0.00 sec)
< exists
not exists⼦查询返回null时判断为假。
mysql> select not exists (select null);
+--------------------------+
| not exists (select null) |
+--------------------------+
exists子查询|      0 |
+--------------------------+
1 row in set (0.00 sec)
以上为个⼈经验,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。如有错误或未考虑完全的地⽅,望不吝赐教。