连接查询是数据库查询语句中使用频率很高的查询方式,下面根据Oracle提供的官方文档学习一下连接查询。 |
一 Equijoins 等值连接
等值连接是条件连接在连接运算符为“=”号时的特例。(相对于非等值连接,如:between...and条件)。它是从关系R与S的广义笛卡尔积中选取A,B属性值相等的那些元组。
SQL> select e.employee_id, e.last_name,
2 e.department_id, d.department_id,
3 d.location_id
4 from employees e, departments d
5 where e.department_id = d.department_id;
EMPLOYEE_ID LAST_NAME DEPARTMENT_ID DEPARTMENT_ID LOCATION_ID
----------- ------------------------- ------------- ------------- -----------
198 OConnell 50 50 1500
199 Grant 50 50 1500
200 Whalen 10 10 1700
201 Hartstein 20 20 1800
......
二 Self joins 自连接
自连接(self join)是SQL语句中经常要用的连接方式,使用自连接可以将自身表的一个镜像当作另一个表来对待,从而能够得到一些特殊的数据。
SELECT e1.last_name||' works for '||e2.last_name
"Employees and Their Managers"
FROM employees e1, employees e2
WHERE e1.manager_id = e2.employee_id
AND e1.last_name LIKE 'R%'
ORDER BY e1.last_name;
Employees and Their Managers
-------------------------------
Rajs works for Mourgos
Raphaely works for King
Rogers works for Kaufling
Russell works for King
三 Cartesian Products 笛卡尔积
如果2个表连接查询而没有连接条件,则oracle返回他们的笛卡尔积。即oracle返回一个表里每一行与另一个表每一行的组合(15 X 4)。
SCOTT@orcl> select count(1) from emp;
COUNT(1)
----------
15
SCOTT@orcl> select count(1) from dept;
COUNT(1)
----------
4
SCOTT@orcl> select count(1) from emp, dept;
COUNT(1)
----------
60
四 Inner Joins 内连接
内连接也叫简单连接,是2个或更多表的关联并且仅返回那些满足连接条件的行。
select e.employee_id, e.last_name,
e.department_id, d.department_id,
d.location_id
FROM employees e JOIN departments d
ON e.department_id = d.department_id;
五 Outer joins 外连接
简单连接的扩展。分为左外连接(Left outer joins)、右外连接(Right outer joins)、全外连接(Full outer joins)和Partitioned Outer Joins(分区外连接,用于数据仓库)。
SELECT d.department_id, e.last_name
FROM departments d LEFT OUTER JOIN employees e
ON d.department_id = e.department_id
ORDER BY d.department_id, e.last_name;
另外一种写法:
SELECT d.department_id, e.last_name
FROM departments d, employees e
WHERE d.department_id = e.department_id(+)
ORDER BY d.department_id, e.last_name;
Oracle 官方推荐使用第一种写法。