暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Oracle-SQL中联用union all与order by的写法

2000


作者:稀饭


本文450字,数理内容较少,泛读需2分钟,精读需5分钟



Oracle-SQL中,当我们要使用union all对两个select语句进行联结时,有同学会写为:


select var_1 as type , count(*) as num from table_1 group by var_1 as type order by num
union all
select var_2 as type , count(*) as num from table_1 group by var_1 as type order by num;


这样写的结果从语法上来看,似乎没有什么问题,但是在执行的时候是会报错的,报错的类型一般在Oracle中是“缺失右括号”。报错的原因是因为多个select语句在union all的时候不是简单的将查询结果拼接起来,而是将sql拼接起来编译(做为一个sql语句),然后去执行。事实上,在有union all的子查询中根本没必要进行排序,因为联合之后又组成了一个新的集合,之前的排序对新集合而言没什么用,直接查询联合之后的新集合然后再进行排序即可。

 

所以,不报错的方法应写为:


select * from 
(
(select var_1 as type , count(*) as num from table_1 group by var_1 as type order by num)
union all
(select var_2 as type , count(*as num from table_1 group by var_1 as type order by num)
);

 

在这样操作之后,就把order by提到了外面进行统一排序,不再会产生错误的执行过程,SQL代码就可以正常运行了。




广告区↓


互联网数据分析岗位求职备战




文章转载自稀饭居然不在家,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论