日期:2014-05-16  浏览次数:20444 次

第七章 显示多个表中的数据

认证目标:


  • 使用同等连接和非同等连接编写select子句访问多个表的数据
  • 使用自连接将表连接到自身
  • 使用外连接查看不满足连接条件的数据
  • 生成两个或多个表的笛卡尔乘积


关系理论的3个支柱:选择、投影和连接。


7.1 使用同等连接和非同等连接编写select语句访问多个表的数据



  • 连接的类型

基本连接分为:同等连接和非同等连接


自然连接:当源表和目标表共享相同名称的列时,就可以执行自然连接,无需指定连接列。

?

select region_name
from regions natural join countries
where country_name='Canada'

?

?

select country_name
from countries natural join regions
where region_name='Americas';

?

当源表和目标表有多个相同列名时,您不需要它们作为连接列,可以使用join...using格式:

?

select region_name
from regions join countries using(region_id)
where country_name='Canada';

?

【注意】:如果Oracle没有强加任何规则表明两个离散表中具有相同名称的列必须彼此相关,如果regions表和countries表中有2列名称相同,那么等于这2列都作为连接条件。

?

join...on格式:不依赖于源表和目标表具有相同名称的列,允许显示表示连接列

?

?

select region_name
from regions a join countries b
on(a.region_id=b.region_id)
where country_name='Canada';

?

【注意】:除了join...on格式,一般不要使用其他格式的自然连接,因为数据库设计师在设计表结构的时候,并不一定保证都能做到不同表相关列的名称都相同。

?

2 外连接


假设employees和departments表由公共的department_id值连接,要想得到含空的department_id值以及departments表中没有department_id值的employess记录,就需要使用到外连接。


3 交叉连接


cross join 与笛卡尔积类似

?

?

select * from regions cross join 
countries where country_id='CA';

?

4 Oracle连接语法:


传统的 Oracle连接语法支持:自然连接、外连接和笛卡尔积连接

?

?

--自然连接
select region_name
from regions,countries
where regions.region_id=countries.region_id;

--外连接
select department_name,last_name
from employees,departments
where employees.department_id(+)=departments.department_id;

--笛卡尔积
select * from regions,countries;
?