1. SQL92:使用(+)创建连接
-
- 在 SQL92 中采用
(+)
代表从表所在的位置。即左或右外连接
中,(+)
表示哪个是从表。 -
Oracle
对 SQL92 支持较好,而 MySQL
则不支持 SQL92 的外连接。 - Oracle实现
#左外连接
SELECT last_name,department_name
FROM employees,departments
WHERE employees.department_id = departments.department_id(+);
#右外连接
SELECT last_name,department_name
FROM employees ,departments
WHERE employees.department_id(+) = departments.department_id;
- SQL92语法实现内连接:如下
练习:查询所有的员工的last_name,department_name信息
SELECT employee_id,department_name
FROM employees e,departments d
WHERE e.`department_id` = d.department_id;
- 而且在 SQL92 中,只有左外连接和右外连接,没有满(或全)外连接。
2. SQL99语法实现多表查询
-
- 使用
JOIN...ON
子句创建连接的语法结构: - SQL99语法中使用
JOIN ...ON
的方式实现多表的查询。这种方式也能解决外连接的问题。MySQL是支持此种方式的。
SELECT table1.column, table2.column,table3.column
FROM table1
JOIN table2 ON table1 和 table2 的连接条件
JOIN table3 ON table2 和 table3 的连接条件
- SQL99语法实现内连接:
SELECT last_name,department_name
FROM employees e INNER JOIN departments d
ON e.`department_id` = d.`department_id`;
SELECT last_name,department_name,city
FROM employees e JOIN departments d
ON e.`department_id` = d.`department_id`
JOIN locations l
ON d.`location_id` = l.`location_id`;
- SQL99语法实现外连接:
练习:查询所有的员工的last_name,department_name信息
- 左外连接:
SELECT last_name,department_name
FROM employees e LEFT JOIN departments d
ON e.`department_id` = d.`department_id`;
- 右外连接:
SELECT last_name,department_name
FROM employees e RIGHT OUTER JOIN departments d
ON e.`department_id` = d.`department_id`;
- 满外连接:mysql不支持
FULL OUTER JOIN
SELECT last_name,department_name
FROM employees e FULL OUTER JOIN departments d
ON e.`department_id` = d.`department_id`;
- SQL99 采用的这种嵌套结构非常清爽、层次性更强、可读性更强,即使再多的表进行连接也都清晰可见。如果你采用 SQL92,可读性就会大打折扣。