Oracle多表查询

开发工具与关键技术:PLSQL Developer ,Oracle知识
作者:丁晓娟
撰写时间:2019-4-10

多表查询:从多个表中查询出数据,通过等值或不等值连接从多个表中查询,还可以使用自连接进行查询,另外也可以使用外连接查询出不满足条件的数据。不过,重要的是要在where子句中写入连接条件,如果查询的列中是两表中相同的列时,要在列名前加上表名前缀,注明查询的是哪个表中的列。简单一点,给表起个别名,加在列名前面,这样的话,既可以简化查询,又可以提高执行效率,自连接的时候也能加以区分。

笛卡尔集:没有连接条件,或者是连接条件错误,都会产生笛卡尔集,一个表中的一条数据和另一个表的所有数据进行一一连接,从而会出现数据紊乱,如果表中的数据过于庞大,还有可能会出现异常,所以我们要避免这种情况出现。
如:
select a.department_id,department_name
from employees a,departments b;
图示1.1:
Oracle多表查询
注:这个只能在表数据不是很多的时候可以测试一下,数据多的情况下就不能随便测试了

等值连接:对两个表中相同的列进行等值连接
如:查询出部门id为60,90的employee_id,last_name,department_name
select employee_id,last_name,a.department_id,department_name
from employees a, departments b
where a.department_id=b.department_id and a.department_id in (60,90);
图示1.2:
Oracle多表查询

不等值连接:对两个表中不同的列进行不等值连接
如:查询出员工表工资在jobs表中job_id为’ST_MAN’的最小工资和最大工资之间的员工信息
select distinct last_name,salary
from employees a,jobs b
where a.salary between b.min_salary and max_salary
and a.job_id= ‘ST_MAN’;
图示1.3:
Oracle多表查询

外连接:可以查询出不满足连接条件的数据,连接符号是’+’
右外连接:返回右表中不满足条件的数据
select department_id,city
from departments a,locations b
where a.location_id(+)=b.location_id and city<>‘Seattle’;
1999语法连接:
select department_id,city
from departments a right outer join locations b
on a.location_id=b.location_id
where city<>‘Seattle’;
图示1.4:
Oracle多表查询

左外连接:返回左表中不满足条件的数据
select department_id,city
from departments a,locations b
where a.location_id=b.location_id(+) and city<>‘Seattle’;
1999语法连接:
select department_id,city
from departments a left outer join locations b
on a.location_id=b.location_id
where city<>‘Seattle’;
图示1.5:
Oracle多表查询

满外连接:返回两个表中不满足条件的数据
select department_id,city
from departments a full outer join locations b
on a.location_id=b.location_id
where city<>‘Seattle’;—1999语法连接,外连接中outer都可以省略不写,不影响结果
图示1.6:
Oracle多表查询

内连接:相当于等值连接
select department_id,city
from departments a inner join locations b
on a.location_id=b.location_id
where city<>‘Seattle’;—1999语法连接,inner可写可不写
图示1.7:
Oracle多表查询

自连接:自己和自己连接(同表连接)
如:查询员工ID号,员工以及他的经理ID号和经理
select a.employee_id “员工ID号”,a.last_name “员工”,
b.employee_id “经理ID号”,b.last_name “经理”
from employees a,employees b
where a.manager_id=b.employee_id and a.department_id=100;
图示1.8:
Oracle多表查询
叉集:和笛卡尔集返回的结果一样
select a.department_id,department_name
from employees a cross join departments b;

自然连接:以两个表中相同的列为条件创建等值连接,并且数据类型也要相同
select department_id,city
from departments a natural join locations b
where city<>‘Seattle’;
图示1.9:
Oracle多表查询
注:如果两个表中有多个相同的列时,查询的时候要注意是否符合题目的要求

Using子句:避免自连接中自动匹配多个相同的列,join和using子句经常同时使用
select last_name,salary
from employees join departments
using(manager_id);
图示2.0:
Oracle多表查询

On子句:可连接多个表
select *
from student a join score b
on a.sno=b.sno
join course c
on b.cno=c.cno;
图示2.1:
Oracle多表查询