sql 中 in 和 not in的问题

经常我们会用到以下情况:
a表一共76条数据,

当我们按type进行查询时:
select * from a where type in (1,2,3,4);
查询出来4条数据,

这时我们想看下剩余的数据是什么情况,想到用not in:

select * from a where type not in (1,2,3,4);

这时,竟然是0条数据,而不是我们以为的 76-4=72条,出什么问题了呢?

这时因为 not in的字段会从有数值的数据中来查询,而不包括空字符串或者null空数据的情况,所以查询时需要加入null的数据:

select * from a where (type not in (1,2,3,4)) or (type is null ) or (type ==’’);
这时,查询出来的就是72条数据了。

很多时候多表查询的时候,可以用not exists来代替

select * from a as a1 where not exists(
select a2.type from a as a2 where a2.type in (1,2,3,4) and a1.type = a2.type
);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值