自连接
查询每个员工的编号、姓名、领导姓名
自连接查询
外连接查询
外连接
连接查询代码
--外连接查询(+号可显示空记录)
select *
from emp e,dept d
where e.deptno(+)=d.deptno;
select e1.empno,e1.ename,e2.ename 领导姓名
from emp e1,emp e2
where e1.deptno(+)=e2.deptno--(+);
--内连接
select * from emp e1 join emp e2 on e1.mgr=e2.empno;--等价于
select * from emp e1 , emp e2 where e1.mgr=e2.empno;
--左外连接
select * from emp e1 left join emp e2 on e1.mgr=e2.empno;--等价于
select * from emp e1 , emp e2 where e1.mgr=e2.empno(+);
--右外连接
select * from emp e1 right join emp e2 on e1.mgr=e2.empno;--等价于
select * from emp e1 , emp e2 where e1.mgr(+)=e2.empno;
--全连接
select * from emp e1 full join emp e2 on e1.mgr=e2.empno;
课下作业题
--课下练习题
---练习
--11. 查询员工编号,姓名,部门编号,部门名称,职务名称并且薪资大于3000 按照薪资降序排列
select empno,ename,emp.deptno,dname,loc,sal
from emp join dept on emp.deptno=dept.deptno
where sal >= 3000
order by sal DESC;
--12.列出受雇日期早于其直接上级的所有员工。
select *
from emp e1,emp e2
where e1.mgr=e2.empno
and e1.hiredate < e2.hiredate;
--13.列出部门名称和这些部门的员工信息,同时列出那些没有员工的部门。
--14.列出所有“CLERK”(办事员)的姓名及其部门名称。
--15.列出所有员工的姓名及其直接上级的姓名。
--16.列出在每个部门工作的员工数量、平均工资和平均服务期限。
select deptno,count(empno),avg(sal),floor(avg(sysdate-hiredate)) 平均天数,
floor(avg(months_between(sysdate,hiredate)/12)) 平均年数
from emp
group by deptno;
--17.列出所有员工的姓名、部门名称和工资。
--18.列出所有部门的详细信息和部门人数。
--21.列出各种工作职责的最低工资。
--22.列出所有员工的年工资,按年薪从低到高排序。
--23. 列出所有员工姓名、职责名称、领导姓名,部门名称、部门地址(没有领导的也列出)
select e1.ename,e1.job,e2.ename,d.dname,d.loc
from emp e1,emp e2,dept d
where e1.mgr=e2.empno(+)
and e1.deptno=d.deptno;
子查询(分页查询)
查找工资最高的员工信息
子查询
查询部门名称和部门人数,用连接查询方式
查询部门名称和部门人数
可以换成子查询方式,即查询内包含查询
子查询
分页查询
直接用分页查询时可以看出行号和工资不对应
分页查询
思路:排完序再加行号
分页查询
接着第二页第三页第四页代码如下
--第二页数据(3,6](rownum只能用>和<和=)
select *
from
(select rownum rn,e.*
from
(select * from emp order by sal) e
where rownum <= 6) a
where rn> 3;
--第三页(7,9]
select *
from
(select rownum rn,e.*
from
(select * from emp order by sal) e
where rownum <= 9) a
where rn> 6;
--第四页(9,12]
select *
from
(select rownum rn,e.*
from
(select * from emp order by sal) e
where rownum <= 12) a
where rn> 9;
由此我们可以得出一个公式:
分页查询公式
到时候写java的时候可以直接用得上,直接复制粘贴即可,代码如下:
select *
from
(select rownum rn,e.*
from
(select * from emp order by sal) e
where rownum <= n*m) a
where rn> (n-1)*m;









网友评论