SQL中in、not in和exists、not exists 的使用注意事项

1.查询A表与B表的关系时,如果条件中使用了exists和not exists,那么在A表和B表关联字段字段名一样的情况下,一定要使用表别名,或者在写关联条件时直接带上表名。

例如:

select * from a where not exists (select 1 from b where id = b.id )

这样写exists就没有意义,查不出数据。

一定要写成这样:

select * from a where not exists (select 1 from b where a.id = b.id )。

2.使用in和not in时A表的字段带不带表名,都一样。

select * from a where id in (select b.id from b)

select * from a where a.id in (select b.id from b)

两个查询是一样的,不过在使用阶段,最好还是带出表名,这样肯定没问题。

总结:in是查询是否包括,而exists是判断是否存在。

3.注意:exists和not exists 两个的集合等于全表,in、not in再加上空值等于全表。所以一定要根据自己的需求使用对应的条件。

select * from a where not exists (select 1 from b where a.id = b.id )

select * from a where  exists (select 1 from b where a.id = b.id )

上面两个查询的集合是A表。

select * from a where a.id in (select b.id from b)

select * from a where a.id not in (select b.id from b)

select * from a where a.id is null .

上面三个查询的集合是A表。

4.关联条件用了两个字段的情况。

select * from a where (a.id,a.name) not in (select b.id , b.name from b)

如果这样查的话,一般B表两个字段都是要有值的,A表两个字段都为空的数据就会被筛掉,只要A表其中一个字段不为空,且满足条件,都会被查询出来。

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值