使用连接来代替in和not in(使用外连接技巧)

本文通过具体实例对比了SQL中不同连接方式(如左外连接、右外连接和内连接)的应用场景及效率,并展示了如何使用这些连接来获取两表间的共有记录、仅A表有而B表没有的记录以及仅B表有而A表没有的记录。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

比如:表A里面的一个字段叫做MOBILE 里面存的记录如下
1
2
3
4
5
6
7
8
1
表B里面的一个字段也叫做MOBILE里面存的记录如下
1
2
3
4
1
9
10
 
(1)我们要查询一下A和B里面都有的,以前我使用的是
select A.mobile from  A where A.mobile in (select B.mobile from B)
出来结果为:
1
1
2
3
4
没关系,去除重复就得到结果1,2,3,4了
现在我们使用另外一种SQL呢:
select A.mobile from A,B where A.mobile=B.mobile
结果为
1
1
2
3
4
1
1
同样滤重得到结果1,2,3,4
(2)第二个实验我们要取一下在A中有的,而在B中没有的,以前我都是使用not in 不要太熟练了,呵呵!不过从来也不考虑个效率。
select  A.mobile from  A where A.mobile not in (select B.mobile from B)
得出结果
5
6
7
8
然后我们再使用连接在处理
select A.mobile from A,B where A.mobile=B.mobile(+) and B.mobile is null
这条语句还可以表示为:
select A.mobile from A left outer  join B on (A.mobile=B.mobile) where B.mobile is null
结果为:
6
5
7
8
(3) 第三个实现我们要取B中有的,而A中没有的,直接用连接了
select B.mobile from B left outer join A on (B.mobile=A.mobile) where A.mobile is null
等价于
select B.mobile from A,B where A.mobile(+)=B.mobile and A.mobile is null 
等价于
select B.mobile from A right outer join B on (A.mobile=b.mobile) where A.mobile is null
 
结果为:
10
9
 
这样的话大家应该对左外连接,右外连接有个理解了吧!!!使用连接肯定是要比not in 的效率高多了,这可不是我说的DBA说的!呵呵!ORACLE10G测试通过!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值