【oracle笔记3】多表查询

*多表查询

  分类:1.合并结果集

     2.连接查询

     3.子查询

  

*合并结果集:要求被合并的表中,列的类型和列数相同。

  *UNION,去除重复行。完全相同的行会被去除

  *UNION ALL:不去除重复行。

  例:select * from ab  UNION ALL  select * from cd;

*连接查询

  分类:1.内连接

     2.外连接:左外,右外,全外。

     3.自然连接

  *内连接:select * from 表1 别名1 inner join 表2 别名2  on 别名1.xx = 别名2.xx;//内连接只会将所有满足条件的记录查询出来,不满足条件的记录不显示。

  *自然连接:select * from 表1 别名1 natural join 表2 别名2 ;//注意:自然连接不用写on条件。直接关联就可以了

  *左外连接:select * from 表1 别名1 left outer join 表2 别名2 on 别名1.xx = 别名2.xx;

    //左表记录无论是否满足条件都会查询出来,右表没有匹配到的行中的列显示为Null。

  *右外连接:select * from 表1 别名1 right outer join 表2 别名2 on 别名1.xx = 别名2.xx;

    //右表记录全显示,左表没匹配到的列显示为null;

  *全外连接:select * from 表1 别名1 full outer join 表2 别名2 on 别名1.xx = 别名2.xx;

  

*子查询:

  特点:查询中嵌套查询,注意select的个数。

  出现位置:1.where后作为条件存在。2.from后作为表存在(多行多列的情况下)

  例子:

    1.查询部门编号为30的员工编号和姓名

     sleect e.eptno,e.ename from (select * from emp where deptno = 30) e;//这里的子查询必需起别名,不然前面不确定要查的是哪个表。

    2.查询本公司工资最高的员工信息

     select * from emp where sal =(select Max(sal) from emp);

    3.列出薪金高于工资平均薪金的所有员工信息,所在部门名称,上级领导,工资等级

        select e.*,d.dname,m.ename,s.grade    //dname=>部门名称,ename=>上级领导,grade=>工资等级

     from emp e left outer join dept d on e.deptno = d.deptno  //连接员工表emp与部门表dept,主键员工编号deptno

        left outer join emp m on e.mgr = m.empno   //员工表emp自身连接

        left outer join salgrade s on e.sal between s.losal and s.hisal  //员工表emp与工资等级表salgrade连接

     where e.sal > (select AVG(sal) from emp);

.

总结:以上列出的只是基本的,关于多表查询还有很多要学习的。现在用着还不太熟练,日积月累,做的项目多了就会慢慢成长起来的,加油加油。

原文地址:https://www.cnblogs.com/shaokai7878/p/9396497.html