为什么使用union all查询出来的值全是后一个语句的

qq_39539374 2018-07-31 01:22:04
select dname,sal from (select deptno,avg(sal) sal from emp group by deptno order by sal) a,dept
WHERE a.deptno=dept.deptno and rownum<=1
union all
select dname,sal from (select deptno,avg(sal) sal from emp group by deptno order by sal desc) a,dept
WHERE a.deptno=dept.deptno and rownum<=1;
这个语句查询出来两个值都是后面一个子查询的结果,分开差能分别查出最高和最低,使用union all 则出现两个最高

select dname from dept where deptno=(select deptno from (select deptno from emp group by deptno order by avg(sal) )where rownum<=1)
union all
select dname from dept where deptno=(select deptno from (select deptno from emp group by deptno order by avg(sal) desc ) where rownum<=1);
这个可以得出正确结果,求大佬解释一下
...全文
387 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
yaiger 2018-07-31
  • 打赏
  • 举报
回复
你没有理解ROWNUM, 在UNION里面用ROWNUM要慎重,只会对最后一条SQL生效。
另外,你的SQL效率不高,数据量不大就算了。数据量大的话考虑first_value分析函数

17,377

社区成员

发帖
与我相关
我的任务
社区描述
Oracle 基础和管理
社区管理员
  • 基础和管理社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧