美文网首页
多行查询、多列查询、相关查询

多行查询、多列查询、相关查询

作者: 骏龙ll | 来源:发表于2019-04-14 21:09 被阅读0次

    说法拆分为逻辑,一种说法可以变为多种说法

    --多行子查询

    in

    any

    all

    --多列子查询

    查询员工工资为其部门最低工资的员工的编号及员工姓名

    select empno,ename

    from emp

    where(deptno,sal) in (select deptno,min(sal) from emp group by deptno)

    --查询可以当表用(需要给查询起表名)

    查询比自己部门平均工资高的员工姓名,工资,部门平均工资

    select ename,sal,avgsal

    from emp e

    join (select deptno,avg(sal) avgsal from emp group by deptno) d

    on e.deptno=d.deptno

    where sal>avgsal

    --相关子查询(子查询中用了父查询中的列)

    -查询每个部门工资最高的员工姓名,工资

    select empno,ename,sal

    from emp e

    where sal=(select max(sal) from emp where deptno=e.deptno)

    -显示部门名称和人数

    传统写法

    select dname,count(empno)

    from emp e

    join dept d

    on e.deptno=d.deptno

    group by dname

    相关子查询写法

    select dname,(select count(empno) from emp where deptno=d.deptno) renshu

    from dept d

    --删除学生表中同名的学员,只保留SNO最大的记录(mysql中不能边从一个表中查询边删除,要重命名一个表,如下)

    delete from s where sno!=ANY(select * from(select max(sno)

    from s

    group by sname) m)

    相关文章

      网友评论

          本文标题:多行查询、多列查询、相关查询

          本文链接:https://www.haomeiwen.com/subject/tgaavqtx.html