Oracle 内连接(inner join)、外连接(outer join)、全连接(full join)

Student表

Color表

Oracle中的连接可分为,内连接(inner join)、外连接(outer join)、全连接(full join),不光是Oracle,其他很多的数据库也都有这3种连接查询方式:

内连接inner join/join

也叫自连接,这是我们经常用到的查询方式,内连接查询只能查询出匹配的记录,匹配不上的记录时无法查询出来的 ,以下三种查询结果一样

select * from student s, color c where s.stuname = c.stuname;

select * from student s inner join color c on s.stuname = c.stuname;

select * from student s join color c on s.stuname = c.stuname;

外连接outer join

可进一步分为左外连接left outer join和右外连接right outer join,(简称左连接left join,右连接 right join)。

左外连接

左连接就是以左边的表(left join 左边的表)为主表,即使有些记录关联不上,主表的信息也能全部查询出来,也就是左边的表数据全部展示,右边表的数据复合条件的展示,不符合条件的以空值代替,适合那种需要求出维度(比如求出所有人员)的需求:

select * from student s left join color c on s.stuname = c.stuname;

等同于select * from student s left outer join color c on s.stuname = c.stuname;

右外连接

如果有需求要求在结果中展现所有的颜色信息,就可以用右连接:

还有另一种写法,可以达到相同的外连接效果:比如左外连接等同于以下的语句:

select * from student s ,color c where s.stuname = c.stuname(+);

同样右连接是这样的:

select * from student s ,color c where s.stuname(+) = c.stuname;

在(+)计算时,哪个带(+)哪个需要条件符合的,另一个全部的。即放左即右连接,放右即左连接。

全连接full join/full outer join

语法是语法为full join ... on ...,全连接的查询结果是左外连接和右外连接查询结果的并集,即使一些记录关联不上,也能够把部分信息查询出来:

产生M+N的结果集,列出两表全部的,不符合条件的,以空值代替。

 

select * from student s full join color c on s.stuname = c.stuname;

select * from student s full join color c on 1=1

笛卡尔乘积cross join

即不加任何条件,达到 M*N 的结果集。

以下两种查询结果一样。

select * from student s cross join color c

select * from student s , color c

注意:如果cross join加上where on s.stuname = c.stuname条件,会产生跟自连接一样的结果(cross join 后加上 on 报错):

加上条件,产生跟自连接一样的结果。

select * from student s cross join color c where s.stuname = c.stuname;

自连接结果集的cross join连接结果

 

总结

ü   所有的join连接,都可以加上类似where a.id='1000'的条件,达到同样的效果。因为on不能做这种判断,只能是

ü   除了cross join不可以加on外,其它join连接都必须加上on关键字,后都可加where条件。

ü   虽然都可以加where条件,但是他们只在标准连接的结果集上查找where条件。比如左外连接的结果没有class的三班,所以如果加 where class.id='C003'虽然在表中有,但在左连接结果集中没有,所以查询后,是没有记录的。

A表有100条数据,B表有80条数据,left join on 1=1,where 1=1的结果是:

应该是笛卡尔积

A表有100条数据,B表有80条数据,left join on 1=2,where 1=1的结果是:

应该是A表的值

测试:

select * from student s left join color c on 1=1 where 1=1

select * from student s left join color c on 1=2 where 1=1

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/30175262/viewspace-1472290/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/30175262/viewspace-1472290/

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值