多表查询的分类:
1. 内连接查询;2. 外连接查询;3. 子查询
1. 内连接查询
表中的行互相连接。在自然连接的基础上加上一个条件判断。只有两个表相匹配的行才能在结果集中出现。返回的结果集选取了两个表中所有相匹配的数据,舍弃了不匹配的数据。内连接是保证两个表中的所有行都满足连接条件。
(1). 隐式内连接:使用where条件消除无用数据
*例子:查询所有员工信息和对应的部门信息
select * from emp, dept where emp.dept_oid = dept.id
(2). 显式内连接: 使用join on 方法消除无用数据
*语法: select 列名 from 表名1 inner join 表名2 on 条件; 其中inner可以省略
*例如 select * from emp join dept on emp.dept_oid = dept.id
2. 外连接查询
不仅包含符号连接条件的行,而且还包含左表(左外连接),右表(右外连接)或两个边接表(全连接)中所有的数据行。outer关键字也可省略
(1). 左外连接:
*语法: select 列名 from 表1 left outer join 表2 on 条件;
*查询的是左表所有数据以及其交集部分。
(2). 右外连接:
*语法: select 列名 from 表1 right outer join 表2 on 条件;
*查询的是右表所有数据以及其交集部分。
3. 子查询
*概念:查询中嵌套查询,称嵌套查询为子查询。
*例子:查询工资中工资最高的人
select * from emp where emp.salary = (select max(salary) from emp);
(1)查询结果是单行多列或一列的:
*<1>子查询可以作为条件,使用基本运算符进行运算;
例子:查询员工工资小于平均工资的人;
select * from emp where emp.salary < (select avg(salary) from emp)
(2)查询结果是多行单列的:
*<1>子查询可以作为条件,使用运算符in来进行运算;
例子:查询财务部和市场部的所有员工信息
select * from emp where name = "财务部" or name = ”市场部“;
select * from emp where dept_id in (select id from dept where name = "财务部" or name = ”市场部“)
(3)子查询的结果是多行多列的:
*<1>子查询可以作为一张虚拟的表参与查询
例子:查询员工入职日期是2011-11-11之后的员工信息和部门信息
select * from dept t1,(selsect * from emp where ewp.join_data > '2011-11-11') t2 where t1.id = t2.dept_id
上式相等于普通连接的: select * from emp t1 , dept t2 where t1.dept_id = t2.id and t1.join_date > '2o11-11-11'