备注:测试数据库版本为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)