in 与not in 的数据集里如果有null 值的情况下返回数据

今天有人提起了 in 与not in 的数据集里如果有null 值的情况下返回数据,not in的怪现象,其实这不是not in 的bug,在sqlserver,mysql,oracle都一样
下面看这个例子

  1.    
  2. create table testa(id int,name varchar(10));  
  3. insert into testa values(1,'anbob.com');  
  4. insert into testa values(2,'weejar');  
  5. insert into testa values(3,null);  
  6. create table testb(id int,name varchar(10));  
  7. insert into testb values(1,'anbob.com');  
  8. insert into testb values(2,'weejar');  
  9. insert into testb values(3,null);  
  10.   
  11. select * from testa where name in(select name from testb);  
  12. select * from testa where name not in(select name from testb);  
  13.   
  14. SQL> select * from testa;  
  15.   
  16. ID NAME  
  17. ---------- ----------  
  18. 1 anbob.com  
  19. 2 weejar  
  20. 3  
  21.   
  22. SQL> select * from testb;  
  23.   
  24. ID NAME  
  25. ---------- ----------  
  26. 1 anbob.com  
  27. 2 weejar  
  28. 3  
  29.   
  30. SQL> select * from testa where name in(select name from stb);  
  31.   
  32. ID NAME  
  33. ---------- ----------  
  34. 1 anbob.com  
  35. 2 weejar  
  36.   
  37. SQL> select * from testa where name not in(select name from testb);  
  38.   
  39. no rows selected  
  40.   
  41. SQL> select * from testa a where not exists(select null from testb b where a.name=b.name);                                                                    
  42.    
  43.         ID NAME  
  44. ---------- ----------  
  45.          3  

为什么一条都没有呢?id 1,2不都有么? 原理是这样的,col in (1,2,null)其实是这么比较
where col=1 or col=2 or col=3 是或的关系,而col not in(1,2,null)是
where col<>1 and col<>2 and col<>null
col<>null 比较会返回unknow ,并且是与的关系,如果有一个条件为nuknow 所以整个条件都为false,
条件比对为true,false,unknow三种情况,所以当用not in 是一定要注意null的存在,可以用not exists替换not in

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值