一、多表查询
所有的连接分析,参考之前随笔:http://www.cnblogs.com/jiangbei/p/7420136.html
1.笛卡尔积
select last_name, department_name
from employees, departments
产生无效的笛卡尔积可以通过where进行过滤
连接查询:
2.等值连接
select e.last_name, d.department_name
from employees e, departments d
where e.department_id = d.department_id
3.外连接
SQL99的连接语法如下:
SELECT table1.column, table2.column
FROM table1
[CROSS JOIN table2] |
[NATURAL JOIN table2] |
[JOIN table2 USING (column_name)] |
[JOIN table2
ON(table1.column_name = table2.column_name)] |
[LEFT|RIGHT|FULL OUTER JOIN table2
ON (table1.column_name = table2.column_name)];
,这里介绍Oracle的左外连接写法:
--左外连接
select e.last_name,e.department_id, d.department_name
from employees e,departments d
where e.department_id = d.department_id(+)
自然连接可以省略连接条件,自动匹配所有相同的行进行笛卡尔积去重!
--自然连接(此种形式下无法使用表别名)
select employees.last_name,employees.department_id, departments.department_name
from employees NATURAL JOIN departments
CROSS JOIN叉集——与笛卡尔积相同
--CROSS JOIN叉集
SELECT last_name, department_name
FROM employees
CROSS JOIN departments ;
自连接
--自连接
SELECT
e1.last_name,e2.last_name,e2.salary,e2.email
FROM
employees e1,employees e2
WHERE
e1.manager_id = e2.employee_id
AND
LOWER(e1.last_name) = ‘chen‘
二、分组函数