3种表连接:Oracle 内连接(inner join)、外连接(outer join)、全连接(full join)

内连接(inner 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 outer join:左边连接就是以左边的表(left join 左边的表)为主表。(返回包括左表中的所有记录和右表中联结字段相等的记录)即使有些记录关联不上,主表的信息也能全部查询出来,也就是左边的表数据全部展示,右边的表数据符合条件的展示,不符合条件的以空值代替,适合那种需要求出维度(比如求出所有人员)的需求:

SELECT * FROM student s left join color c no s.stuname = c.stuname; 等同于

SELECT * FROM student s left join color c on s.stuname = c.stuname

右外连接right outer join:(返回包括右表中的所有记录和左表中联结字段相等的记录)如果有需求要求写在结果中展示所有的颜色信息,就可以用右连接:还有另一种写法,可以达到相同的外连接效果:比如左外连接等同于以下的语句:

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:(返回两个表的行:left join+right 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’虽然在表中有,但在左连接结果集中没有,所以查询后,是没有记录的。

猜你喜欢

转载自blog.csdn.net/CQL_K21/article/details/88621183