在講外連接之前,先舉例介紹內連接,也就是一般的相等連接。
select * from a, b where a.id = b.id;
對於外連接,Oracle中可以使用“(+)”來表示,9i可以使用LEFT/RIGHT/FULL OUTER JOIN,下面將配合實例一一介紹。
1. LEFT OUTER JOIN:左外關聯
SELECT e.last_name, e.department_id, d.department_name
FROM employees e
LEFT OUTER JOIN departments d
ON (e.department_id = d.department_id);
等價於
SELECT e.last_name, e.department_id, d.department_name
FROM employees e, departments d
WHERE e.department_id=d.department_id(+);
結果為:所有員工及對應部門的記錄,包括沒有對應部門編號department_id的員工記錄。
2. RIGHT OUTER JOIN:右外關聯
SELECT e.last_name, e.department_id, d.department_name
FROM employees e
RIGHT OUTER JOIN departments d
ON (e.department_id = d.department_id);
等價於
SELECT e.last_name, e.department_id, d.department_name
FROM employees e, departments d
WHERE e.department_id(+)=d.department_id;
結果為:所有員工及對應部門的記錄,包括沒有任何員工的部門記錄。
3. FULL OUTER JOIN:全外關聯
SELECT e.last_name, e.department_id, d.department_name
FROM employees e
FULL OUTER JOIN departments d
ON (e.department_id = d.department_id);
結果為:所有員工及對應部門的記錄,包括沒有對應部門編號department_id的員工記錄和沒有任何員工的部門記錄。