Oracle OCP笔记(17)多个表的连接查询

本文详细介绍了Oracle中的表连接查询方法,包括传统Oracle连接语法中的自然连接、外连接和交叉连接,以及ANSI SQL:1999标准连接语法下的各种连接方式。通过示例说明了不同连接类型的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Oracle OCP笔记(17)多个表的连接查询



一.传统的Oracle连接语法
(1).自然连接
select regions.region_name, countries.country_name
  from regions, countries
 where regions.region_id = countries.region_id;


(2).外连接
-- 左外连接(同时返回左边表因不满足连接条件而被排除在外的行)
select last_name, department_name
  from departments, employees
 where departments.department_id = employees.department_id(+);


-- 右外连接(同时返回右边表因不满足连接条件而被排除在外的行)
select last_name, department_name
  from employees, departments
 where employees.department_id(+) = departments.department_id;


***传统的连接语法不支持全外连接


(3).交叉连接(笛卡尔乘积)
select * from regions, countries;


二.ANSI SQL:1999标准连接语法
SELECT table1.column, table2.column
  FROM table1 [NATURAL JOIN table2]|
              [JOIN table2 USING (column_name)]|
              [JOIN table2 ON (table1.column_name = table2.column_name)]|
              [LEFT|RIGHT|FULL OUTER JOIN table2 ON (table1.column_name = table2.column_name)]|
              [CROSS JOIN table2]
 WHERE ...


(1).自然连接
-- 纯自然连接(NATURAL JOIN),依据两个表中具有相同名称的列
select *
  from regions natural join countries 
 where country_id = 'US';


-- 自然连接(JOIN ... USING)
select *
  from location join countries using (country_id);


-- 自然连接(JOIN ... ON)
select *
  from departments d join employees e 
       on (e.employee_id = d.department_id);


-- 多路连接查询
select r.region_name, c.country_name, l.city, d.department_name
  from departments d
       join locations l on (l.location_id = d.location_id)
       join countries c on (c.country_id = l.country_id)
       join regions r on (r.region_id = c.region_id);


select r.region_name, c.country_name, l.city, d.department_name
  from departments d
       join locations l using (location_id)
       join countries c using (country_id)
       join regions r using (region_id);


(2).外连接
-- 左外连接(LEFT OUTER JOIN)(同时返回左边表因不满足连接条件而被排除在外的行)
select e.employee_id, e.department_id emp_dept_id, d.department_id dept_dept_id, d.department_name
  from departments d left outer join employees e
       on (d.department_id = e.department_id)
 where d.department_name like 'P%';


-- 右外连接(RIGHT OUTER JOIN)(同时返回右边表因不满足连接条件而被排除在外的行)
select e.employee_id, e.department_id emp_dept_id, d.department_id dept_dept_id, d.department_name
  from employees e right outer join departments d 
       on (e.department_id = d.department_id)
 where d.department_name like 'P%';


-- 全外连接(FULL OUTER JOIN)(左外连接和右外连接的组合结果)
select table1.column, table2.column
  from table1 full outer join table2
       on (table1.column = table2.column);


***传统的连接语法不支持全外连接


(3).交叉连接(笛卡尔乘积)(CROSS JOIN)
select table1.column, table2.column
  from table1 cross join table2;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值