美文网首页
MySQL 找到包含最大值和最小值的记录

MySQL 找到包含最大值和最小值的记录

作者: 只是甲 | 来源:发表于2020-11-11 10:29 被阅读0次

    备注:测试数据库版本为MySQL 8.0

    如需要scott用户下建表及录入数据语句,可参考:
    scott建表及录入数据sql脚本

    一.需求

    查找表中的"两级"值。例如,找出表EMP中具有最高工资和最低工资的员工。

    二.解决方案

    2.1 子查询方法

    select ename
     from  emp
    where  sal in ( (select min(sal) from emp),
                    (select max(sal) from emp) );
    

    测试记录

    mysql> select ename
        ->  from  emp
        -> where  sal in ( (select min(sal) from emp),
        ->                 (select max(sal) from emp) );
    +-------+
    | ename |
    +-------+
    | SMITH |
    | KING  |
    +-------+
    2 rows in set (0.00 sec)
    

    2.2 MySQL 8.0 窗口函数方法

    select ename
      from (
    select ename,sal,
           min(sal) over w as 'min_sal',
           max(sal) over w as 'max_sal'
      from emp
      window w as ()
           ) x
    where sal in (min_sal,max_sal);
    

    测试记录

    mysql> select ename
        ->   from (
        -> select ename,sal,
        ->        min(sal) over w as 'min_sal',
        ->        max(sal) over w as 'max_sal'
        ->   from emp
        ->   window w as ()
        ->        ) x
        -> where sal in (min_sal,max_sal);
    +-------+
    | ename |
    +-------+
    | SMITH |
    | KING  |
    +-------+
    2 rows in set (0.00 sec)
    
    

    相关文章

      网友评论

          本文标题:MySQL 找到包含最大值和最小值的记录

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