SQL语句02(连表查询)
---恢复内容开始---
sql1992
sql分类
1.笛卡尔积 (表乘表)
例:select * from emp,dept;
2.等值连接 表的连接条件使用“=”
例:select * from emp,dept where emp.deptno = dept.deptno;
3.非等值连接 表的连接条件使用“>、>=、 <、<=、!=、any等”
例:select e.ename,sg.grade from emp e,salgrade sg where e.sal between sg.losal and sg.hisal;
4.自连接 自己连接自己
例:select e1.ename || ' 的上司是 '|| e2.ename from emp e1,emp e2 where e1.mgr = e2.empno;
5.外连接:在等值基础上,确保一张表(主表)的记录都存在 从表满足则匹配,不满足补充null
1.左外连接,“(+)”在等号右边
例:select * from emp e,dept d where d.deptno = e.deptno(+);
2.右外连接,“(+)”在等号左边
例:select * from emp e,dept d where d.deptno(+) = e.deptno;
3.“(+)”在哪一边的列,该表就补充null
sql1999
sql分类
1.cross join 交叉连接 (笛卡尔积) ,不需要on关键字
例: select * from emp cross join dept
2.natural join 自然连接 (找两个表中相同的列,进行等值匹配),不需要on关键字
例: select * from emp natural join dept
3.inner join 内连接
1)必须有on关键字,on表示连接条件
2)inner关键字可以省略
--等值连接
select e.ename,d.dname from emp e INNER JOIN dept d on e.deptno = d.deptno where e.sal > 2000
--非等值连接
select e.ename,s.grade from emp e INNER JOIN salgrade s on e.sal between s.losal and s.hisal
--自连接
select e1.ename || '的上司是' || e2.ename from emp e1 INNER JOIN emp e2 on e1.mgr = e2.empno
4.outer join 外连接,outer关键字可以省略
1) left outer join
例:select * from emp e LEFT OUTER JOIN dept d on e.deptno = d.deptno
2) right outer join
例:select * from emp e RIGHT OUTER JOIN dept d on e.deptno = d.deptno
3) full outer join
例:select * from emp e FULL OUTER JOIN dept d on e.deptno = d.deptno
--如何进行多表连接
--查询员工的姓名、薪水、部门名称及工资等级
select e.ename, e.sal, d.dname, s.grade
from emp e, dept d, salgrade s
where e.deptno = d.deptno
and e.sal between s.losal and s.hisal
select e.ename, e.sal, d.dname, s.grade
from emp e
join dept d
on e.deptno = d.deptno
join salgrade s
on e.sal between s.losal and s.hisal
--子查询
--在where中使用的子查询
例:
--查询部门名称为RESEARCH、SALES
select *
from emp
where deptno in
(select deptno from dept where dname in ('RESEARCH', 'SALES'))
--查询有哪些人的薪水是在整个雇员的平均薪水之上的
select ename,empno, sal, sal+nvl(comm,0)
from emp
where sal+nvl(comm,0)>(select avg(sal+nvl(comm,0)) from emp);
--查在雇员中有哪些人是经理人
select empno, ename
from emp
where empno in (
select distinct mgr from emp
);
--找出部门编号为20的所有员工中收入最高的职员
select * from emp
where sal >= all(
select sal
from emp
where deptno = 20)
and
deptno = 20
--在from后面使用子查询
例:
--我们要求每个部门平均薪水的等级
select t1.deptno, t1.savg, s.grade
from (select deptno, avg(sal) savg from emp group by deptno) t1
join salgrade s
on t1.savg between s.losal and s.hisal
--求每个部门薪水的平均等级
select t1.deptno, avg(t1.grade)
from (select e.deptno, s.grade
from emp e, salgrade s
where e.sal between s.losal and s.hisal) t1
group by t1.deptno
---恢复内容结束---