如果表A中某条记录在表B中没有对应的记录存在,而又想列出表A中所有的记录,此时采用内连接将无法达到目的。可以采用外连接的方法, 在WHERE子句中,表B相应字段名的右方添加符号:(+),则Oracle在连接时则会自动生成一条空记录和表A的记录进行连接).
注意:如果两个表没有任何关联时查询结果是一个笛卡尔及。
(1) 等值内联接
select * from S,T where S.y=T.z
x y z k
100 a c 500
101 b d 600
102 c e 700
103 d f 800
S表 T表
x y z k
102 c c 500
103 d d 600
S_T表
(2) 非等值内连接
select * from s,t where t.z>s.y
100 a c 500
101 b c 500
100 a d 600
101 b d 600
102 c d 600
100 a e 700
101 b e 700
102 c e 700
103 d e 700
100 a f 800
101 b f 800
102 c f 800
103 d f 800
(3) 左外连接(z中有,y中没有以null填充)left out join
select * from s,t where t.z(+)=s.y
100 a null null
101 b null null
102 c c 500
103 d d 600
(4) 右外连接
right out join select * from s,t where t.z=s.y(+)
102 c c 500
103 d d 600
null null e 700
null null f 800
(5) 全连接
full out join
select * from s full outer join t on(s.y=t.z)
102 c c 500
103 d d 600
101 b null null
100 a null null
null null f 800
null null e 700
SELECT e.last_name, e.department_id, d.department_name
FROM employees e LEFT OUTER JOIN departments d ON (e.department_id = d.department_id);
等价于:
SELECT e.last_name, e.department_id, d.department_name FROM employees e, departments d WHERE e.department_id=d.department_id(+);
介绍一种特殊的连接(自连接)
当一个表的插入行之间有了关系时就需要自连接
比如员工表中,经理也是属于公司的员工
select a.ename,b.ename from emp a,emp b where a.empno=b.mgr;
b表中的经理(id)等于a表中的(id) a表看作是经理表,b表看作是员工表,形成经理和员工的对应关系