左外连接: 当where e.deptno=d.deptno不成立的时候,等号左边所代表的表记录 任然被包含
tablea left join tableb on 条件
右外连接: 当where e.deptno=d.deptno不成立的时候,等号右边所代表的表记录 任然被包含
tablea rigth join tableb on 条件
使用右外连接,达到需要的效果,语句如下:
select d.deptno 部门号,d.dname 部门名称,count(e.empno) 人数
from emp e right join dept d
on e.deptno=d.deptno
group by d.deptno,d.dname
order by d.deptno ;
查询结果如下:
select e.ename||'的领导是'||b.ename
from emp e,emp b
where e.mgr=b.empno;
FORD的领导是JONES
SCOTT的领导是JONES
JAMES的领导是BLAKE
TURNER的领导是BLAKE
MARTIN的领导是BLAKE
自连接操作不太适合操作太大的表,否则查询的时候产生的笛卡尔集会随着表记录增长而成平方级别的增长
5 层次查询(遍历的是一棵树,利用递归)
分析上面案例,得到领导和下属关系的树结构图如下:
前一次操作的员工号是后一次操作的领导号
select level,empno,ename,sal,mgr
from emp
connect by prior empno=mgr
start with mgr is null
order by level; ---> 可以修改成 order by 1; 1表示查询条件的第一个字段,即level
执行的过程:
1. KING: start with mgr is null ---> empno=7839
2. where mgr = 7839; ---> 7566 7698 7782
3. where mgr in (7566 7698 7782)
select e.empno,e.deptno,e.ename,e.sal,d.avgsal
from emp e,(select deptno,avg(sal)avgsal from emp group by deptno) d
where e.deptno= d.deptno and e.sal > d.avgsal;