解决mysql使用not in 包含null值的问题
注意!!!
select*fromuserwhereuidnotin(a,b,c,null);
这个sql不回返回任何结果。要避免notin的list中出现null的情况。
另外:
–如果null参与算术运算,则该算术表达式的值为null。(例如:+,-,*,/加减乘除)
–如果null参与比较运算,则结果可视为false。(例如:>=,<=,<>大于,小于,不等于)
–如果null参与聚集运算,则聚集函数都置为null(使用isnull(字段,0)等方式可以避免这种情况)。除count(*),count(1),count(0)等之外(count(字段)字段为null的行不参与计数)。
--如果在notin子查询中有null值的时候,则不会返回数据。
补充:MySQLin,notin,exists,notexists与null的恩恩怨怨
null这个东西在数据里算是个奇葩,在比较中也比较特殊,下面记录总结一下在in,notin,exists,notexists中null对判断结果的影响。
做一些描述声明,在比较符左边的我们称为左比较符,在比较符右边的我们称为右比较符,例如1in(1,2),那么in左边的1是左比较符,in右边的(1,2)是右比较符。
1.in
1.1当左比较符是null,任何情况下都返回null。
mysql>selectnullin(1,2); +---------------+ |nullin(1,2)| +---------------+ |NULL| +---------------+ 1rowinset(0.00sec) mysql>selectnullin(1,2,null); +--------------------+ |nullin(1,2,null)| +--------------------+ |NULL| +--------------------+ 1rowinset(0.00sec)
1.2当右比较符包含null,只当左比较符不为null,且右比较符包含左比较符时,返回1,其他情况均返回null。
mysql>selectnullin(1,2,null); +--------------------+ |nullin(1,2,null)| +--------------------+ |NULL| +--------------------+ 1rowinset(0.00sec) mysql>select3in(1,2,null); +-----------------+ |3in(1,2,null)| +-----------------+ |NULL| +-----------------+ 1rowinset(0.00sec) mysql>select1in(1,2,null); +-----------------+ |1in(1,2,null)| +-----------------+ |1| +-----------------+ 1rowinset(0.00sec)
2.notin
2.1当左比较符为null,任何情况都返回null。
mysql>selectnullnotin(1,2,null); +------------------------+ |nullnotin(1,2,null)| +------------------------+ |NULL| +------------------------+ 1rowinset(0.00sec) mysql>selectnullnotin(1,2); +-------------------+ |nullnotin(1,2)| +-------------------+ |NULL| +-------------------+ 1rowinset(0.00sec)
2.2当右比较符包含null,当右比较符包含左比较符时返回0,其他情况均返回null。
mysql>select1notin(1,2,null); +---------------------+ |1notin(1,2,null)| +---------------------+ |0| +---------------------+ 1rowinset(0.00sec) mysql>select1notin(2,3,null); +---------------------+ |1notin(2,3,null)| +---------------------+ |NULL| +---------------------+ 1rowinset(0.00sec)
3.exists
exists子查询返回null时判断为真。
mysql>selectexists(selectnull); +----------------------+ |exists(selectnull)| +----------------------+ |1| +----------------------+ 1rowinset(0.00sec)
4.notexists
notexists子查询返回null时判断为假。
mysql>selectnotexists(selectnull); +--------------------------+ |notexists(selectnull)| +--------------------------+ |0| +--------------------------+ 1rowinset(0.00sec)
以上为个人经验,希望能给大家一个参考,也希望大家多多支持毛票票。如有错误或未考虑完全的地方,望不吝赐教。