MySQL数据库概述及数据准备
MySQL数据库常用命令
MySQL数据库查看表结构
MySQL查询字段
MySQL条件查询
MySQL排序
MySQL函数
MySQL分组函数/聚合函数/多行处理函数
MySQL分组查询
MySQL连接查询
MySQL子查询
MySQL UNION
MySQL中limit的用法
MySQL表
MySQL存储引擎
MySQL事务
MySQL索引
MySQL视图
MySQL DBA命令
MySQL数据库设计的三大范式
MySQL数据库练习题

MySQL子查询

子查询就是嵌套的select语句,可以理解为子查询是一张表。

在where语句中使用子查询,也就是在where语句中加入select语句

● 查询员工信息,查询哪些人是管理者,要求显示出其员工编号和员工姓名

实现思路:

1、首先取得管理者的编号,去除重复的

select distinct mgr from emp where mgr is not null;

distinct 去除重复行

2、查询员工编号包含管理者编号的

select empno, ename from emp where empno in(select mgr from emp where mgr is not null);

● 查询哪些人的薪水高于员工的平均薪水,需要显示员工编号,员工姓名,薪水实现思路

1、取得平均薪水

select avg(sal) from emp;

2、取得大于平均薪水的员工

select empno, ename, sal from emp where sal > (select avg(sal) from emp);

在from语句中使用子查询,可以将该子查询看做一张表

●  查询员工信息,查询哪些人是管理者,要求显示出其员工编号和员工姓名

1、首先取得管理者的编号,去除重复的

select distinct mgr from emp where mgr is not null;

2、将以上查询作为一张表,放到from语句的后面

使用92语法:
select e.empno, e.ename from emp e, (select distinct mgr from emp where mgr is not null) m where e.empno=m.mgr;
使用99语法:
select e.empno, e.ename from emp e join (select distinct mgr from emp where mgr is not null) m on e.empno=m.mgr;

● 查询各个部门的平均薪水所属等级,需要显示部门编号,平均薪水,等级编号

实现思路

1、首先取得各个部门的平均薪水

select deptno, avg(sal) avg_sal from emp group by deptno;

2、将部门的平均薪水作为一张表与薪水等级表建立连接,取得等级

select deptno,avg(sal) avg_sal from emp group by deptno;
select * from salgrade;
select a.deptno,a.avg_sal,g.grade from (select deptno,avg(sal) avg_sal from emp group by deptno ) a join salgrade g on a.avg_sal between g.losal and hisal;

在select语句中使用子查询

● 查询员工信息,并显示出员工所属的部门名称

第一种做法,将员工表和部门表连接

select e.ename, d.dname from emp e, dept d where e.deptno=d.deptno

第二种做法,在select语句中再次嵌套select语句完成部分名称的查询

select e.ename, (select d.dname from dept d where e.deptno=d.deptno) as dname from emp e

全部教程