Oracle数据库——多表查询、层次查询

一、什么是多表查询?

从多个表中获取数据
在这里插入图片描述

二、笛卡尔集

在这里插入图片描述

三、连接的类型

1、等值连接

示例:查询员工信息,要求显示:员工号,姓名,月薪,部门名称

select e.empno,e.ename,e.sal,d.dname
from emp e, dept d
where e.deptno = d.deptno; 

在这里插入图片描述

2、不等值连接

查询员工信息,要求显示:员工号,姓名,月薪,薪水级别

select e.empno,e.ename,e.sal,s.grade
from emp e, salgrade s
where e.sal between s.losal and s.hisal;

在这里插入图片描述

3、外连接

示例:按部门统计员工人数,要求显示:部门号,部门名称,人数

select d.deptno 部门号, d.dname 部门名称, count(e.empno) 人数
from emp e, dept d
where e.deptno = d.deptno
group by d.deptno, d.dname;

在这里插入图片描述

  • 核心:通过外连接,把对于连接条件不成立的记录,仍然包含在最后的结果中

  • 左外连接:当连接条件不成立的时候,等号左边的表仍然被包含

select d.deptno 部门号,d.dname 部门名称, count(e.empno) 人数
from emp e, dept d
where e.deptno = d.deptno(+)
group by d.deptno, d.dname;

在这里插入图片描述

  • 右外连接:当连接条件不成立的时候,等号右边的表仍然被包含
select d.deptno 部门号,d.dname 部门名称, count(e.empno) 人数
from emp e, dept d
where e.deptno(+) = d.deptno
group by d.deptno, d.dname;

在这里插入图片描述

4、自连接

示例:按员工姓名和员工的老板姓名

select e.ename 员工姓名, b.ename 老板姓名
from emp e, emp b 
where e.mgr = b.empno;

在这里插入图片描述

  • 核心:通过别名,将同一张表视为多张表

  • 自连接存在的问题:不适合操作大表

  • 解决办法:层次查询


四、层次查询

  • 某些情况下,层次查询可以替代自连接

  • 本质上,是一个单表查询
    在这里插入图片描述

层次查询的原理:
在这里插入图片描述

select level, empno, ename, sal, mgr
from emp
connect by prior empno = mgr
start with mgr is null
order by level;

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/hyh17808770899/article/details/106793443