1.自连接
自连接是指在同一张表之间的连接查询
它主要用在自参照表上,用来显示上下级关系或者层次关系。
自参照表:指在不同列之间具有参照关系或主从关系的表。
例如:
select a.ename from emp a,emp b
where a.empno = b.mgr
and b.ename = 'blake';
2.内连接、外连接和全连接
语法:
select table1.column,table2.column
from table1 [inner|left|right|full] join table2
on table1.column1 = table2.column2;
3.使用(+)操作符
在Oracle9i之前,当执行外连接的时,都是使用连接操作符(+)来完成的。
尽管可以使用操作符(+)执行外连接操作,但Oracle9i开始建议使用outer join执行外连接。
使用(+)操作符执行外连接的语法如下:
select table1.column,table2.column from
table1,table2
where table1.column(+) = table.column2;
当使用(+)操作符执行外连接时,应该将该操作符放在显示较少行(完全满足连接条件行)的一端。
当使用(+)操作符时,必须注意以下事项:
(1)(+)操作符只能出现在where子句中,并且不能与outer join 语法同时使用。
(2)当使用(+)操作符执行外连接时,如果在where子句中有多个条件,则必须要在所有条件中都包含(+)操
作符。
(3)(+)操作符只适用于列,而不能用在表达式上。
(4)(+)操作符不能与or和in操作符一起使用。
(5)(+)操作符只能用于实现左外连接和有外连接,而不能用于完全外连接。
<1>使用(+)操作符执行左外连接
select a.dname,b,ename from dept a, emp b
where a.deptno = b.deptno(+)
and b.deptno(+) = 10;
<2>使用(+)操作符执行右外连接
select a.dname,b.ename from dept a ,emp b
where a.deptno(+) = b.deptno
and a.deptno(+) = 10
order by a.dname;
左、右、全连接测试:
1.创建表
create table test1(id number, name varchar2(10));
create table test2(id number);
2.插入模拟数据
insert into test1(id, name) values(1, 'name1');
insert into test1(id, name) values(2, 'name1');
insert into test1(id, name) values(3, 'name1');
insert into test1(id, name) values(4, 'name1');
insert into test1(id, name) values(5, 'name1');
insert into test1(id, name) values(6, 'name1');
insert into test2(id) values(1);
insert into test2(id) values(2);
insert into test2(id) values(3);
insert into test2(id) values(7);
insert into test2(id) values(8);
insert into test2(id) values(9);
3.左外连接: (+)在右边
--代表除了显示匹配相等连接条件的信息之外,还显示左条件所在的表中无法匹配相等连接条件的信息。
select a.id, b.id
from test1 a
left [outer] join test2 b on a.id = b.id;
select a.id, b.id
from test1 a, test2 b
where a.id = b.id(+);
4.右外连接: (+)在左边
--代表除了显示匹配相等连接条件的信息之外,还显示右条件所在的表中无法匹配相等连接条件的信息。
select a.id, b.id
from test1 a, test2 b
where a.id(+) = b.id;
select a.id, b.id
from test1 a
right [outer] join test2 b on a.id = b.id;
5.全连接
select a.id, b.id
from test1 a
full [outer] join test2 b on a.id = b.id;