子查询

子查询
	select语句中嵌套select语句,被嵌套的select语句是子查询
	子查询可以出现在select、from、where
	
	案例:找出高于平均薪资的员工信息
		where后面嵌套子查询
	mysql> select * from emp where sal>(select avg(sal) from emp);
	
	案例:找出每个部门平均薪水的薪资等级
		from后面嵌套子查询
	第一步:
		找出每个部门的平均薪资
		mysql> select deptno,avg(sal) as avgsal from emp group by deptno;
	第二步:
		将第一步查询结果当作临时表t,让t表和salgrade s表连接
		mysql> select t.*,s.grade 
			   from (select e.deptno,avg(sal) as avgsal from emp e group by deptno) t 
			   join salgrade s on t.avgsal between s.losal and s.hisal;
			   
	案例:找出每个部门薪资等级的平均值
	mysql> select e.deptno,avg(s.grade) avggrade 
		   from emp e join salgrade s on e.sal between losal and hisal 
		   group by e.deptno;
		   
	案例:找出每个员工所在的部门名称,要求显示员工名和部门名
		select后面嵌套子查询
	mysql> select e.ename,d.dname from emp e join dept d where e.deptno=d.deptno;
	或:   select e.ename,(select d.dname from dept d where e.deptno=d.deptno) as dname from emp e;
	

  

posted @ 2021-10-18 17:07  石乐智先生  阅读(59)  评论(0编辑  收藏  举报