MySQL 子查询(嵌套的 select 语句)

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

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

子查询在 WHERE 中的语法格式如下:
WHERE <表达式> <操作符> (子查询)
其中,操作符可以是比较运算符(<、<=、>、>=、=、<>)和 IN、NOT IN、EXISTS、NOT EXISTS 等关键字。

1)IN | NOT IN

当表达式与子查询返回的结果集中的某个值相等时,返回 TRUE,否则返回 FALSE;若使用关键字 NOT,则返回值正好相反。

2)EXISTS | NOT EXISTS

用于判断子查询的结果集是否为空,若子查询的结果集不为空,返回 TRUE,否则返回 FALSE;若使用关键字 NOT,则返回的值正好相反。

查询员工信息,查询哪些人是管理者,要求显示出其员工编号和员工姓名
实现思路:
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);

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

查询员工信息,查询哪些人是管理者,要求显示出其员工编号和员工姓名
首先取得管理者的编号,去除重复的
select distinct mgr from emp where mgr is not null;
将以上查询作为一张表,放到 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 * 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;

3、在 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;

posted @ 2022-07-26 16:16  鹿先森JIAN  阅读(4678)  评论(0编辑  收藏  举报