n  概述

表连接分为内连接和外连接

n  内连接

内连接实际上就是利用where子句对两张表形成的笛卡尔集进行筛选,我们前面学习的查询都是内连接,也是在开发过程中用的最多的连接查询。

基本语法:

select  字段1,字段2,. . .  from 表1  inner join 表2  on  条件 . . .

select emp.ename,dept.dname from emp,dept where emp.deptno=dept.deptno; 等同于

select emp.ename,dept.dname from emp inner join dept on emp.deptno=dept.deptno;

n  外连接

①左外连接     (如果左侧的表完全显示我们就说是左外连接)

②右外连接      (如果右侧的表完全显示我们就说是右外连接)

③完全外连接    (完全显示两个表,没有匹配的记录置为空)

 

SQL> create table stu(id number,name varchar2(32));

SQL> create table exam(id number,grade number);

 

实际应用

显示所有人的成绩,如果没有成绩,也要显示该人的姓名和ID号,成绩显示为空。

select stu.name,stu.id,exam.grade from stu,exam where stu.id=exam.id;

上面我们使用的内连接:它的特点是只有两张表同时匹配,才被选择。

 

①使用左外连接:

select stu.name,stu.id,exam.grade from stu left join exam on stu.id=exam.id;

如果stu(左表)的记录没有和exam任何一条记录匹配,也要被选中。

怎么判断一张表是左边,如果在left join左边,就是左表。

另外一种写法:

select stu.name,stu.id,exam.grade from stu,exam where stu.id=exam.id(+);

②右连接(显示所有成绩,如果没有名字匹配,显示空)

 

select stu.name,stu.id,exam.grade from stu right join exam on stu.id=exam.id;

③完全外连接(显示所有成绩和所有人的名字,如果相应的匹配值,则显示空)

说明:有外联,指定是右边的表如果没有和左边任何一条记录匹配,也要被选中。

另外还有一种写法:

select stu.name,stu.id,exam.grade from stu,exam where stu.id(+)=exam.id;

把(+)写在左边,就表示右外联。

小结:实际上左外联和右外联是可以互为转换

显示所有人的成绩,如果没有成绩,也要显示该人的姓名和ID号,成绩显示为空。

(1)select stu.name,stu.id,exam.grade from stu right join exam on stu.id=exam.id;

(2)select stu.name,stu.id,exam.grade from stu,exam where stu.id(+)= exam.id;

(3)select stu.name,stu.id,exam.grade from exam left join stu on stu.id=exam.id;

(4)select stu.name,stu.id,exam.grade from stu,exam where exam.id= stu.id(+);

 

完全外连接(显示所有成绩和所有人的名字,如果相应的匹配值,则显示空)

即:两个表查询,不管有没有匹配,全都显示。

select stu.name,stu.id,exam.grade from stu full outer join exam on stu.id=exam.id;