外连接的理解:
就是具有外键关系的两张表之间的关系,比如学生表student里面的studentId可能在分数表score里面是一个外键stuid,正常情况下,学生表里面有了学生的信息数据之后,那么在score表里面也应该对应的有信息,但是现在存在的问题就是有了studentid不一定会在分数表中有数据,因为可能现在没有考试,或者是考试的时候有些人没有去...,,为了反映出来这两张表之间的差异就需要使用语句把它们给查询出来这个时候就出现了外连接了,外连接分为三种,一种是自连接,一种是左连接,一种是右连接,可是如果我们按照它们的原理去记忆的话非常的繁琐,这个时候这样记:左连接左全,右连接右全。这句话的意思就是说如果是左连接,那么就是左表的记录是全的也就是说左表是主表,而右表是从表是以主表的主键为外键的表,后面的一句话也是同样的道理,只不过是换一个说法而已。
因此左连接左全,右连接右全这句话就可以很简单的帮助我们在使用外连接的时候很清楚的区分自己应该如何使用它们。
例如两张表:
create table student(
studentid number(11) primary key,
name varchar2(20)
);
create table score(
scoreid number(15) primary key,
stuid number(11),
point number(3)
);
alter table SCORE
add constraint F_STUDENTID foreign key (STUID)
references STUDENT (STUDENTID);
例如要查询出来考试的时候有谁没有考试那么这个时候需要使用到这两张表,这样就需要使用外连接了,使用外连接的时候有两种方法,一种是使用where子句和"+"一起使用的外连接,另外一种是使用left/right join xxxtable on xxxcondition 下面就分别使用者两种方式把结果给查询出来,不过这两个是不可以混合使用的,只能够使用其中一个。
select * from score;
--left join
select s.studentid as "学号",s.name as "姓名" ,sc.point as "分数"
from student s left join score sc on s.studentid = sc.stuid;
--where 和 ”+“
select s.studentid as "学号" ,s.name as "姓名",sc.point as "分数"
from student s,score sc where sc.stuid(+)=s.studentid;
--right join
select s.studentid as "学号" ,s.name as "姓名",sc.point as "分数"
from score sc right join student s on s.studentid = sc.stuid;
--where 和 ”+“
select s.studentid as "学号",s.name as "姓名",sc.point as "分数"
from student s,score sc where s.studentid=sc.stuid(+);
--full join
select s.studentid as "学号",s.name as "姓名",sc.point as "分数"
from student s full join score sc on s.studentid = sc.stuid;
关于使用(+)的一些注意事项:
1.(+)操作符只能出现在where子句中,并且不能与outer join语法同时使用。
2. 当使用(+)操作符执行外连接时,如果在where子句中包含有多个条件,则必须在所有条件中都包含(+)操作符
3.(+)操作符只适用于列,而不能用在表达式上。
4.(+)操作符不能与or和in操作符一起使用。
5.(+)操作符只能用于实现左外连接和右外连接,而不能用于实现完全外连接。