在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(*);

以上两点是在执行sql查询的时候做的一点总结,希望大家能够提出更多关于null的查询需要注意的地方出来,以避免一些不必要的错误与困惑。

以上是在sqlserver 的实验,同时在oracle中也有同样的问题需要注意,但是有一点不同第三条插入的语句中将是得到一个null值数据。看如下实验:
(1)准备数据
CREATE TABLE tbl_user (
 id NUMBER(9)  NOT NULL ,
 name nvarchar2(15) ,
  pid nvarchar2(20)
);

insert into tbl_user (id,name,pid)values(1,'test1','no1');
insert into tbl_user (id,name,pid)values(2,'test2',null);
insert into tbl_user (id,name,pid)values(3,'test3','');
(2)执行查询
select count(*),count(pid),count(decode(pid,null,' ',pid)) from tbl_user where pid not in(null);
--结果:0   0   0
select count(*),count(pid),count(decode(pid,null,' ',pid)) from tbl_user where pid in(null);
--结果:0   0   0
select count(*),count(pid),count(decode(pid,null,' ',pid)) from tbl_user where pid is null;
--结果:2   0   2
select count(*),count(pid),count(decode(pid,null,' ',pid)) from tbl_user where pid is not null;
--结果:1   1   1
select count(*),count(pid),count(decode(pid,null,' ',pid)) from tbl_user;
--结果:3   1   3

导致oracle和sqlserver 结果差异是因为oracle认为''等同于null,所以decode(pid,null,' ',pid)的''之间务必要加空格。

posted on 2007-07-09 14:11  flyrat  阅读(2968)  评论(2编辑  收藏  举报

导航