SQL中Null的注意点
时 间:2016-12-14 08:04:59
作 者:宏鹏 ID:21115 城市:上海
摘 要:SQL中使用Null需要注意的地方
正 文:
在 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值进行处理。
Access软件网QQ交流群 (群号:54525238) Access源码网店
常见问答:
技术分类:
源码示例
- 【源码QQ群号19834647...(12.17)
- 【Access选项卡示例】Ac...(09.09)
- 【Access源码示例】按输入...(09.02)
- 【Access日期区间段查询】...(08.29)
- 【Access日期区间段查询】...(08.27)
- Access怎样才能实现日期时...(08.21)
- 【Access定时打开查询】A...(08.19)
- Access生成固定数量的记录...(08.13)
- Access怎样才能实现日期时...(08.12)
- Access利用导航窗体控件对...(08.03)
学习心得
最新文章
- Access表中的字段名、字段标题...(09.19)
- Access快速开发平台--更改“...(09.18)
- 【中秋及国庆优惠】Access培训...(09.15)
- Access如何将日期型的数值转换...(09.14)
- 英文输入法输入数据中存在单引号引起...(09.11)
- 【Access选项卡示例】Acce...(09.09)
- 让Access光标停留在指定的控件...(09.07)
- 关于Access查询条件里使用通配...(09.06)
- Access报表偷懒制作法--Ac...(09.05)
- Access快速开发平台--窗体数...(09.04)