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

相關文章
相關標籤/搜索