Chinaunix首页 | 论坛 | 博客
  • 博客访问: 773446
  • 博文数量: 180
  • 博客积分: 4447
  • 博客等级: 上校
  • 技术积分: 1582
  • 用 户 组: 普通用户
  • 注册时间: 2006-04-03 14:51
文章分类

全部博文(180)

文章存档

2014年(6)

2013年(8)

2011年(125)

2009年(35)

2008年(1)

2007年(5)

分类: Oracle

2009-03-04 18:23:08

使用连接来代替in,not in(使用外连接技巧)
 
比如:表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测试通过!
阅读(1102) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~