没有合适的资源?快使用搜索试试~ 我知道了~
sql的查询中,遇见null值时要注意对count的影响,以避免一些不必要的错误与困惑
资源推荐
资源详情
资源评论
在sql中null值对count,in的影响
先做一下以下实验:
(1)准备数据环境
CREATE TABLE [tbl_user] (
[id] [int] IDENTITY (1, 1) NOT NULL ,
[name] [nvarchar] (15),
[pid] [nvarchar] (20) NULL
) ON [PRIMARY]
GO
insert into tbl_user (name,pid)values('test1','no1')
insert into tbl_user (name,pid)values('test2',null)
insert into tbl_user (name,pid)values('test3','')
(2)执行查询.
select count(*),count(pid),count(isnull(pid,'')) from tbl_user where pid not in(null)
--结果:0 0 0
select count(*),count(pid),count(isnull(pid,'')) from tbl_user where pid in(null)
--结果:0 0 0
select count(*),count(pid),count(isnull(pid,'')) from tbl_user where pid is null
--结果:1 0 1
select count(*),count(pid),count(isnull(pid,'')) from tbl_user where pid is not null
--结果:2 2 2
select count(*),count(pid),count(isnull(pid,'')) from tbl_user
--结果:3 2 3
所以,
1.null在in中还是在not in中都找不到任何数据,这一点很重要,经常适用(not) in 查询的时候要注意保证该列不含有null值,否则将导致如果有null值存在,查询不到任何数据;最好的方法是加个条件is not null的条件在子查询中;
2.利用count进行计算行数的时候,对指定字段的不会将null值计算在内,如果需要将null值的行也计算在内(通常是需要的),需要考虑将null值转化为空,如isnull(pid,'')再统计,或者直接适用count(1),或count(*);
先做一下以下实验:
(1)准备数据环境
CREATE TABLE [tbl_user] (
[id] [int] IDENTITY (1, 1) NOT NULL ,
[name] [nvarchar] (15),
[pid] [nvarchar] (20) NULL
) ON [PRIMARY]
GO
insert into tbl_user (name,pid)values('test1','no1')
insert into tbl_user (name,pid)values('test2',null)
insert into tbl_user (name,pid)values('test3','')
(2)执行查询.
select count(*),count(pid),count(isnull(pid,'')) from tbl_user where pid not in(null)
--结果:0 0 0
select count(*),count(pid),count(isnull(pid,'')) from tbl_user where pid in(null)
--结果:0 0 0
select count(*),count(pid),count(isnull(pid,'')) from tbl_user where pid is null
--结果:1 0 1
select count(*),count(pid),count(isnull(pid,'')) from tbl_user where pid is not null
--结果:2 2 2
select count(*),count(pid),count(isnull(pid,'')) from tbl_user
--结果:3 2 3
所以,
1.null在in中还是在not in中都找不到任何数据,这一点很重要,经常适用(not) in 查询的时候要注意保证该列不含有null值,否则将导致如果有null值存在,查询不到任何数据;最好的方法是加个条件is not null的条件在子查询中;
2.利用count进行计算行数的时候,对指定字段的不会将null值计算在内,如果需要将null值的行也计算在内(通常是需要的),需要考虑将null值转化为空,如isnull(pid,'')再统计,或者直接适用count(1),或count(*);
资源评论
joy_yyan
- 粉丝: 0
- 资源: 2
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
最新资源
- 第四次作业4 +984+98+7
- kernel-ml-5.17.1-1.el7.elrepo.x86-64.rpm
- AUTOSAR CP TR Release Overview
- flannel-flannel-cni-plugin-v1.4.1-flannel1-amd64.tar.gz
- delphi面试题.pdf
- kernel-ml-4.17.11-1.el7.elrepo.x86-64.rpm
- 第三次作业42 527487543
- kernel-lt-5.4.134-1.el7.elrepo.x86-64.rpm
- kernel-lt-5.4.109-1.el7.elrepo.x86-64.rpm
- 2323235534634634636
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功