在 SQL 语句中, NULL 值与字符列中的空格, 数字中的零, 字符列中的 NULL ASCII 字符都不相同. 大家在写SQL时都会有遇到NULL的经历,例如在一个table插入NULL,与NULL作比较等等.下面介绍SQL 语句中, NULL 值的使用
一、Null不支持大小/相等判断
1、下面的2个查询,不管表 users 中有多少条记录,返回的记录都是0行
select * from users where deleted_at = null;
select * from users where deleted_at != null;
用常规的比较操作符(normal conditional operators)来将 null 与其他值比较是没有意义的。 Null 也不等于 Null
2、将某个值与 null 进行比较的正确方法是使用 is 关键字, 以及 is not 操作符:
select * from users where deleted_at is null;
二、not in 与 Null
1、not in 实例
子查询(subselect)是一种很方便的过滤数据的方法。例如,如果想要查询没有任何包的用户,可以编写下面这样一个查询:
select * from users where id not in (select user_id from packages)
2、假若 packages 表中某一行的 user_id 是 null 的话,返回结果是空的!
3、出现上述的原因
例如
select * from users where id not in (1, 2, null)
这个SQL语句会等效于
select * from users where id != 1 and id != 2 and id != null
4、in查询
select * from users where id in (1, 2, null)
等效于
select * from users where id = 1 or id = 2 or id = null
三、GROUP BY会把NULL分到一个组
insert into test values (NULL,12), (NULL,13) select * from test select Name,SUM(age)as sumage from test group by Name
结果
四、Null与排序
在排序时, null 值被认为是最大的. 在降序排序时(descending),null值排在了最前面。
例如、下面这个查询是为了根据得分显示用户排名, 但它将没有得分的用户排到了最前面!
select name, points from users order by 2 desc; – points 为 null 的记录排在所有记录之前!
解决方法:排序前事先对null值进行处理。