having
-
where 后面只能写普通字段的条件 不能写聚合函数的条件
-
having
: 结合group by使用,后面写聚合函数的条件 -
各种关键字的顺序:
select .....from 表名 where ..... group by.... having .... order by.... limit ....;
- 查询每个部门的平均工资 要求平均工资高于2000
select deptno,avg(sal) a from emp
group by deptno having a>2000;
- 查询每个部门的平均工资,只查询工资在1000-3000之间的员工,并且过滤掉平均工资低于2000的部门
select deptno,avg(sal) a from emp
where sal between 1000 and 3000
group by deptno having a>=2000;
- 查询每个部门的工资总和,只查询有上级领导的员工并且要求工资总和大于5400,最后按照工资总和降序排序,只查询结果中的第一条数据
select deptno,sum(sal) s from emp
where mgr is not null
group by deptno having s>5400
order by s desc limit 0,1;
子查询(嵌套查询)
- 查询工资高于平均工资的员工信息
select avg(sal) from emp;
select * from emp where sal>(select avg(sal) from emp);
- 查询工资最高的员工信息
select max(sal) from emp;
select * from emp where sal=(select max(sal) from emp);
- 查询工资高于2号部门平均工资的员工信息
select * from emp
where sal>(select avg(sal) from emp where deptno=2);
- 查询和孙悟空相同工作的其它员工信息
select job from emp where ename='孙悟空';
select * from emp
where job=(select job from emp where ename='孙悟空')
and ename!='孙悟空';
- 查询白骨精的部门信息(需要用到dept表)
select deptno from emp where ename='白骨精';
select * from dept
where deptno=(select deptno from emp where ename='白骨精');
- 查询有员工的部门信息(想办法过滤掉4号部门)
select distinct deptno from emp; //得到员工表中出现的部门
select * from dept
where deptno in(select distinct deptno from emp);
关联关系
- 创建表时,表与表之间存在的业务关系称为关联关系
- 有哪些关系:
- 1对1: 有AB两张表,A表中一条数据对应B表中的一条,同时B表中的一条对应A表中的1条;
- 1对多: 有AB两张表,A表中一条数据对应B表中的多条,同时B表中的一条对应A表中的1条;
- 多对多: 有AB两张表,A表中一条数据对应B表中的多条,同时B表中的一条对应A表中的多条;
关联查询
- 同时查询多张表数据的查询方式称为关联查询
- 进行关联查询时
必须
写关联关系,如果不写会得到两张表的乘积(称为笛卡尔积),工作中切忌不要出现. - 关联查询的查询方式有三种:
关联查询之等值连接
- 格式:
select * from A, B where A.x = B.x and A.age=18;
- 查询每个员工的姓名和对应的部门名
select e.ename,d.dname
from emp e,dept d
where e.deptno=d.deptno;
- 查询工资低于2000块钱的员工姓名,工资和部门名
select e.ename,e.sal,d.dname
from emp e,dept d
where e.deptno=d.deptno and e.sal<2000;
关联查询之内连接
- 格式:
select * from A join B on A.x=B.x where A.age=18;
- 查询每个员工的姓名和对应的部门名
select e.ename,d.dname
from emp e join dept d
on e.deptno=d.deptno; // on 后面是关联条件
- 查询工资低于2000块钱的员工姓名,工资和部门信息
select e.ename,e.sal,d.*
from emp e join dept d
on e.deptno=d.deptno
where e.sal<2000;
- 等值连接和内连接查询的都是两张表的交集数据
关联查询之外连接
- 如果需要查询一张表的全部数据和另外一张表的交集数据使用外连接
- 格式:
select * from A left/right join B on A.x=B.x where A.age=18;
- 查询所有部门的名称和对应的员工名字
select e.ename,d.dname
from emp e right join dept d
on e.deptno=d.deptno;
- 查询所有员工姓名和对应的部门信息
insert into emp (empno,ename) values(100,'灭霸');
select e.ename,d.*
from emp e left join dept d
on e.deptno=d.deptno;
关联查询总结:
- 总共有三种查询方式: 等值连接/内连接/外连接
- 如果需要查询两张表的交集数据使用等值连接或内连接(推荐)
- 如果查询的是一张表的全部数据和另外一张表的交集数据则使用外连接
如果这篇文章有帮助到您,请简单给个赞吧,谢谢~