oracle连接分为:
左外连接:左表不加限制,保留左表的数据,匹配右表,右表没有匹配到的行中的列显示为null。
右外连接:右表不加限制,保留右表的数据。匹配左表,左表没有匹配到的行中列显示为null。
完全外连接:左右表都不加限制。即右外连接的结果为:左右表匹配的数据+左表没有匹配到的数据+右表没有匹配到的数据。
连接的语法:
left/right/full outer join ...on
left/right/full join ...on
左外连接:左表不加限制,保留左表的数据,匹配右表,右表没有匹配到的行中的列显示为null。
右外连接:右表不加限制,保留右表的数据。匹配左表,左表没有匹配到的行中列显示为null。
完全外连接:左右表都不加限制。即右外连接的结果为:左右表匹配的数据+左表没有匹配到的数据+右表没有匹配到的数据。
连接的语法:
left/right/full outer join ...on
left/right/full join ...on
(+)号的作用:+号可以理解为补充的意思,加在那个表的列上就代表这个表的列为补充。加在右表的列上代表右表为补充,为左连接。加在左表的列上代表左表为补充,为右连接。注意:完全外连接中不能使用+号。
select d.deptno,d.dname,count(e.empno)
from emp e,dept d
where e.deptno(+)=d.deptno
group by d.deptno,d.dname
order by d.deptno desc
;
等值连接/非等值连接/内连接:只会查询出多张表中,根据某个字段匹配,符合条件的记录,不符合条件的记录是不会存在的
左外连接[是oracle专用的,不是SQL99规则]:
使用Oracle的scott用户下的表, dept表当成主表查询 emp副表查询
--查询每个部门的人数有多少
select d.deptno,d.dname,count(e.empno)
from emp e,dept d
where e.deptno(+)=d.deptno
group by d.deptno,d.dname
order by d.deptno desc
;
右外连接
select dept.deptno "部门号",dept.dname "部门名",count(emp.empno) "人数"
from dept,emp
where emp.deptno(+) = dept.deptno
group by dept.deptno,dept.dname;
左外连接
--按部门10,20,30,40号,统计各部门员工人数,要求显示部门号,部门名,人数,且按人数降序排列
select dept.deptno "部门号",dept.dname "部门名",count(emp.empno) "人数"
from dept,emp
where dept.deptno = emp.deptno(+)
group by dept.deptno,dept.dname
order by 3 desc;
--显示每个员工的上级
select e1.ename||'的上级是'||e2.ename
from emp e1,emp e2
where e1.mgr=e2.empno(+);
注意:自连接也用到内连接和外连接