連接查詢是數據庫查詢語句中使用頻率很高的查詢方式,下面根據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 官方推薦使用第一種寫法。
https://www.linuxprobe.com/oracle-connection-query.html