【NULL】Where子句中=1 与!=1UNION后的结果是全集么?——NULL小伙惹的祸

与“NULL小伙”有关的趣闻很多,有兴趣的朋友可以先看一下这个文章热热身。
《【问题处理】“NOT IN”与“NULL”的邂逅》(http://space.itpub.net/519536/viewspace-627169)

1.创建测试表T并初始化三条数据,注意一条数据是NULL值。
sec@ora10g> create table t (x number);

Table created.

sec@ora10g> insert into t values (1);

1 row created.

sec@ora10g> insert into t values (null);

1 row created.

sec@ora10g> insert into t values (3);

1 row created.

sec@ora10g> commit;

Commit complete.

2.查看T表中的数据并确认T表中的总数据条数
sec@ora10g> select * from t;

         X
----------
         1

         3

sec@ora10g> select count(*) from t;

  COUNT(*)
----------
         3

没有问题。

3.有趣的事情发生了
sec@ora10g> select count(*) from (select * from t where x = 1 union all select * from t where x != 1);

  COUNT(*)
----------
         2

按照正常的逻辑思考,对于同一张表T的x字段等于1和不等于1的数据集合应该是全集,为什么此时返回的记录只有2条。

4.问题同样处在NULL值上
sec@ora10g> select * from t where x = 1;

         X
----------
         1

sec@ora10g> select * from t where x != 1;

         X
----------
         2

对于条件“x != 1”,因为NULL是一个不确定的状态,因此此时NULL值是不被检索到的。

5.同样的道理like与not like对于含有NULL值的表进行统计时,也不是全集
sec@ora10g> select count(*) from (select * from t where x like '1' union all select * from t where x not like '1');

  COUNT(*)
----------
         2

6.小结
每当出现所谓“灵异事件”时,我们需要的只是冷静的思考,任何异常现象都可以追本溯源。
少一分浮躁,多一分实操。

Good luck.

secooler
10.06.09

-- The End --

请使用浏览器的分享功能分享到微信等