马士兵老师oracle视频学习笔记(二)
子查询:
select deptno,ename,sal from emp where sal in(select max(sal) from emp group by deptno);
上面这个写法有问题,如果其他部门有个人的工资也在这三个薪水里面,那么信息也会被选出。
select ename,sal from emp join (select max(sal) maxsal ,deptno from emp group by deptno) t on (emp.deptno = t.deptno and emp.sal = t.maxsal);
上面代码的意思是:找出每个部门工资最高的人的姓名和薪水。
select grade,ename,sal from emp e join (select max(sal) maxsal,deptno from emp group by deptno) t on (e.deptno = t.deptno and e.sal = t.maxsal) join salgrade g on (e.sal >= losal and e.sal <= hisal);
上面代码的意思是:找出每个部门工资最高的人的姓名和薪水和薪水等级
1999年新标准:
等值连接:
select ename,dname from emp,dept where emp.deptno = dept.deptno;
select ename,dname from emp join dept on emp.deprno = dept.deptno;
select ename,dname from emp join dept using(deptno); //不推荐
上面三句sql等同。
非等值连接:
select sal,grade from emp join salgrade on sal between losal and hisal;
select ename,dname,sal,grade from emp join dept on emp.deptno = dept.deptno join salgrade on sal between losal and hisal where ename not like '_A%';
select e1.ename,e2.ename from emp e1 left join emp e2 on e1.mgr = e2.empno; 左连接(将左边多余的取出来)
select ename,dname from emp e right join dept d on e.deptno = d.deptno; 右连接(将右边多余的取出来)
select ename,dname from emp e full join dept d on e.deptno = d.deptno; 全连接(将左右多余的都取出来)