Day04 多表查询
1. 笛卡尔集
笛卡尔集会在下面条件下产生:
- 省略连接条件
- 连接条件无效
- 所有表中的所有行互相连接
为了避免笛卡尔集, 可以在 WHERE加入有效的连接条件。
2. Oracle连接
![](https://images2015.cnblogs.com/blog/326197/201704/326197-20170403225343472-1438349219.png)
3. 等值连接
![](https://images2015.cnblogs.com/blog/326197/201704/326197-20170403225405769-106236981.png)
4. 表的别名
![](https://images2015.cnblogs.com/blog/326197/201704/326197-20170403225418160-180531702.png)
![](https://images2015.cnblogs.com/blog/326197/201704/326197-20170403225446785-2047559913.png)
5. 连接多个表
![](https://images2015.cnblogs.com/blog/326197/201704/326197-20170403225524097-1743380007.png)
6. 非等值连接
![](https://images2015.cnblogs.com/blog/326197/201704/326197-20170403225545800-1276751267.png)
7. 内连接和外连接
![](https://images2015.cnblogs.com/blog/326197/201704/326197-20170403225618441-1245838642.png)
8. 自连接
![](https://images2015.cnblogs.com/blog/326197/201704/326197-20170403225633941-1615427494.png)
9. 1999连接
![](https://images2015.cnblogs.com/blog/326197/201704/326197-20170403225701800-73432044.png)
SQL语句的多表查询方式:
例如:按照department_id查询employees(员工表)和departments(部门表)
的信息。
方式一(通用型):SELECT ... FROM ... WHERE
SELECT e.last_name,e.department_id,d.department_name
FROM employees e,departments d
where e.department_id = d.department_id
方式二:SELECT ... FROM ... NATURAL JOIN ...
有局限性:会自动连接两个表中相同的列(可能有多个:department_id和manager_id)
SELECT last_name,department_id,department_name
FROM employees
NATURAL JOIN departments
方式三:SELECT ... JOIN ... USING ...
有局限性:好于方式二,但若多表的连接列列名不同,此法不合适
SELECT last_name,department_id,department_name
FROM employees
JOIN departments
USING(department_id)
方式四:SELECT ... FROM ... JOIN ... ON ...
常用方式,较方式一,更易实现外联接(左、右、满)
SELECT last_name,e.department_id,department_name
FROM employees e
JOIN departments d
ON e.department_id = d.department_id
--内连接
1)
--等值连接
--不等值连接
2)
--非自连接
--自连接
--外连接
--左外连接、右外连接、满外连接