时间:2021-07-01 10:21:17 帮助过:3人阅读
select deptno from emp where ename=‘CLARK‘
select sal from emp where ename =‘CLARK‘
-- 第三步:分别查询,部门和CLARK一样的,工资比他少的
select ename ,sal,deptno from emp where deptno = (select deptno from emp where ename=‘CLARK‘) and sal < (select sal from emp where ename =‘CLARK‘)
这上面查询过程中:子查询可以独立运行,并且是先于外查询的,
(2)相关子查询
--查询[工资高于其所在部门20的平均工资的]那些员工
select * from emp e1 where e1.deptno = 20 and sal >(select avg(sal) from emp e2 where e2.deptno = 10)
在这条语句中,子查询内部的WHERE关键字后的条件中外查询的条件参与,不能单独运行
二:根据查询结果
(1)单行子查询:子查询结果只有一条数据
(2)多行子查询:子查询结果有多条记录,此时之间不能用= < >,要借助 ANY ALL IN 来实现
例如:
(1)单行子查询:
--查得所有【比“CLARK”工资高的】员工的信息 select * from emp select sal from emp where ename =‘CLARK‘ --2450 select * from emp where sal > 2450.00 子查询结果只有一条 select * from emp where sal > (select sal from emp where ename =‘CLARK‘)
(2)多行子查询
--查询工资低于任何一个“CLERK”的工资的雇员信息。 select * from emp where sal< (select max(sal) from emp where job =‘CLERK‘) select sal from emp where job =‘CLERK‘ --1300 1100 950 800 select * from emp where sal< any(select sal from emp where job =‘CLERK‘) --查询[工资比所有的“SALESMAN”都高的]雇员的编号、名字和工资。 --ALL >ALL select empno,ename,sal from emp where sal >(select max(sal) from emp where job =‘SALESMAN‘) select empno,ename,sal from emp where sal > ALL(select sal from emp where job =‘SALESMAN‘) select max(sal) from emp where job =‘SALESMAN‘ --查询部门20中职务同部门10的雇员一样的雇员信息。 select job from emp where deptno = 20 --CLERK ANALYST select job from emp where deptno = 10 --MANAGER PRESIDENT CLERK ---- CLERK MANAGER -- IN 等于其中任何一个 select * from emp where deptno = 20 and job in (select job from emp where deptno = 10)
Mysql的子查询相关知识,少但是精
标签:dep max 关键字 div any 条件 pre select sql