SQL 中 Null 值使用时须要注意的地方

1、Null不支持大小/相等判断html


一、下面的2个查询,无论表 users 中有多少条记录,返回的记录都是0行spa

select * from  users where deleted_at = null;code

select * from  users where deleted_at != null;orm

用常规的比较操做符(normal conditional operators)来将 null 与其余值比较是没有意义的。 Null 也不等于 Nullhtm


二、将某个值与 null 进行比较的正确方法是使用 is 关键字, 以及 is not 操做符:排序

select * from users where deleted_at is null;
 
 

 

2、not in 与 Nullget


 
一、not in 实例
 
子查询(subselect)是一种很方便的过滤数据的方法。例如,若是想要查询没有任何包的用户,能够编写下面这样一个查询:
 

select * from users where id not in (select user_id from packages)it

 

二、倘若 packages 表中某一行的 user_id 是 null 的话,返回结果是空的!io


三、出现上述的缘由
 
 
例如
select * from users where id not in (1, 2, null)
 
这个SQL语句会等效于

select * from users where id != 1 and id != 2 and id != nullclass


 
四、in查询
 
select * from users where id in (1, 2, null)
 
等效于
 
select * from users where id = 1 or id = 2 or id = null

 


 
3、GROUP BY会把NULL分到一个组
 

 

4、Null与排序
 
 
在排序时, null 值被认为是最大的. 在降序排序时(descending),null值排在了最前面。



参考资料:SQL 中 Null 值使用时须要注意的地方   http://www.studyofnet.com/news/1037.html

相关文章
相关标签/搜索