如果条件调换过来, 查询结果就没有问题。 现在我们查询有package的用户.
| select * from users where id in (select user_id from packages) |
同样我们可以使用简单的例子:
| select * from users where id in (1, 2, null) |
这条SQL被转换为:
| select * from users where id = 1 or id = 2 or id = null |
因为 where 子句中是一串的 or 条件,所以其中某个的结果为 null 也是无关紧要的。非真(non-true)值并不影响子句中其他部分的计算结果,相当于被忽略了。
Null与排序
在排序时, null 值被认为是最大的. 在降序排序时(descending)这会让你非常头大,因为 null值排在了最前面。
下面这个查询是为了根据得分显示用户排名, 但它将没有得分的用户排到了最前面!
| select name, points from users order by 2 desc; – points 为 null 的记录排在所有记录之前! |
解决这类问题有两种思路。最简单的一种是用 coalesce 消除 null的影响:
| – 在输出时将 null 转换为 0 : select name, coalesce(points, 0) from users order by 2 desc; – 输出时保留 null, 但排序时转换为 0 : select name, points from users order by coalesce(points, 0) desc; |
还有一种方式需要数据库的支持,指定排序时将 null 值放在最前面还是最后面:
| select name, coalesce(points, 0) from users order by 2 desc nulls last; |
当然, null 也可以用来防止错误的发生,比如处理除数为0的数学运算错误。
被 0 除
除数为0是一个非常 egg-painfull 的错误。昨天还运行得好好的SQL,突然被0除一下子就出错了。一个常用的解决方法是先用 case 语句判断分母(denominator)是否为0,再进行除法运算。
| select case when num_users = 0 then 0 else total_sales/num_users end; |
ase 语句的方式其实很难看,而且分母被重复使用了。如果是简单的情况还好,如果分母是个很复杂的表达式,那么悲剧就来了: 很难读,很难维护和修改,一不小心就是一堆BUG.
这时候我们可以看看 null 的好处. 使用 nullif 使得分母为0时变成 null. 这样就不再报错, num_users = 0 时返回结果变为 null.
| select total_sales/nullif(num_users, 0); |
nullif 是将其他值转为 null, 而Oracle的 nvl 是将 null 转换为其他值。
如果不想要 null,而是希望转换为 0 或者其他数, 则可以在前一个SQL的基础上使用 coalesce函数:










