分类
内连接
隐式内连接: 使用where条件消除无用数据
-- 查询所有员工信息和对应的部门信息
select * from emp,dept where emp.dept_id = dept.id;
显式内连接
- 语法:select 字段 from 表名 inner join 另一表名 on 条件语句
-- 查询所有员工信息和对应的部门信息
select * from emp inner join dept on emp.dept_id = dept.id;
-- 不加inner也可以
select * from emp join dept on emp.dept_id = dept.id;
外连接
左外连接
-- 查询所有员工信息和对应的部门信息,如果没有部门信息显示为NULL
select * from emp left outer join dept on emp.dept_id = dept.id;
-- 不加outer也可以
select * from emp left join dept on emp.dept_id = dept.id;
右外连接
-- 查询所有员工信息和对应的部门信息,如果没有部门信息则不显示
select * from emp right outer join dept on emp.dept_id = dept.id;
-- 不加outer也可以
select * from emp right join dept on emp.dept_id = dept.id;
子查询
套娃查询
子查询的结果是单行单列的
-- 查询员工当中工资最高的员工信息
select * from emp where salary = (select max(salary) from emp);
-- 查询员工当中小于平均工资的人
select * from emp where salary < (select avg(salary) from emp));
子查询的结果是多行单列的
子查询可以作为条件, 使用运算符in来判断
--查询“财务部”和“市场部所有的员工信息”
-- 首先查出财务部和市场部在dept表中的id
select id from dept where name = '财务部' or name = '市场部';
-- 然后根据dept_id 查出对应的员工信息
select * from emp where dept_id = 2 or dept = 3;
select * from emp where dept_id in (2,3);
-- 合并成一条
select
*
from
emp
where
dept_id in (select id from dept where name = '财务部' or name = '市场部');
子查询的结果是多行多列的
--查询员工入职日期是2011-11-11日之后的员工信息和部门信息
--首先查询员工入职日期是2011-11-11日之后的员工信息
select * from emp where join_date > '2011-11-11'
-- 然后将这条SQL查询出来的结果作为一张虚拟表
select
*
from
dept t1 , (select * from emp where join_date > '2011-11-11') t2
where
t1.id = t2.dept.id
-- 也可以使用普通内连接的方式查询
select
*
from
emp , dept
where
emp.dept_id = dept.id
and
emp.join_date > '2011-11-11'