内连接查询
- 隐式内连接:使用where条件来消除无用的数据;
- select * from 表名,表名 where 条件;
1. select * from emp,dapt where emp.'dept_id'=dept.'id';
//使用别名
2. select t1.--,
t1.--,
t2.--
from emp t1,
dapt t2
where t1.'dept_id'=t2.'id';
- 显式内连接:显式指定内连接的方式
- 语法:select 字段列表 from 表名1 inner join 表名2 on 条件;
1.select * from emp inner(可选) join dept on emp.'dept_id'=dept.id;
select * from emp join dept on emp.'dept_id'=dept.id;
3.内连接查询条件:
- 从哪些表中查询数据;
- 查询的条件是什么;
- 明确要查询哪些字段;
外连接查询
- 左外连接;查询的是左表的全部信息和左表与右表的交集部分;
- 语法:select 字段列表 from 表1 left (outer) join 表2 on 条件;
//查询所有的信息
select * from dept; //查询所有的部门信息
select * from emp; //查询所有的员工信息
//查询所有员工的部门信息,如果有部门则查询部门信息,如果没有部门,则显示部门名称
select t1.*,t2.'name'
from emp t1 left join dept t2
on t1.'dept_id'=t2.id;
- 右外连接;查询的是右表的全部信息和右表与左表的交集部分
- 语法:select 字段列表 from 表1 right (outer) join 表2 on 条件;
select * from dept t2 right join emp t1 on t1.'dept_id'=t2.id;
子查询:就是查询中嵌套查询,称嵌套查询为子查询
- 单行单列子查询
//查询工资最高的员工信息
//1.查询出最高的工资
select max(salary) from emp;
//2.查询出员工信息,并且工资等于上面查询的工资
select * from emp where emp.'salary'=(max(salary)); //max(salary)指第一条语句中查询出来的最高工资
//一条SQL完成查询
select * from emp where emp.'salary'=(select max(salary) from emp);
- 子查询的不同情况
- 子查询的结果是单行单列的
- 子查询可以作为条件,使用运算符去判断;(< > >= =< =)
//查询员工工资小于平均工资的人
select * from emp where emp.salary < (select avg(salary) from emp);
- 子查询的结果是多行单列的
- 子查询可以作为条件,使用运算符in来判断
//查询财务部和市场部的所有员工信息
select id from dept where name=‘财务部’ or name=‘市场部’ ;
select * from emp where dept_id=2 or dept_id=3;//2,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-10之后的员工信息和部门信息
select * from dept t1,(select * from emp where emp.'join_date'>'2011-11-10'
) t2 where t1.id=t2.dept_id;
//普通内连接查询
select * from emp t1,dept t2 where t2.id=t1.‘dept_id’ and t1.'join_date'>'2011-11-10';