UNION ALL和ORDER BY 的搭配使用注意事项

1 篇文章 0 订阅

一.先连接后排序

1.连接排序时,无论有多少个union/union all的部分,只有最后一个union/union all部分才能拥有一个order by子句

2.union/union all的order by子句只能通过列号或别名来标示你要排序的字段

例: select t1.account_id account_id,t1.account_name account_name from t1

        union/union all

        select t2.account_id account_id,t2.account_name account_name from t2

        order by 1/account_id;

注:"/"是或的意思,不代表是语法或具有含义。

二.先排序后连接

1.多结果集在被union/union all连接后仍然保持原有的排序,需要把结果集放在子查询中

例: select * from

(select t1.account_id account_id,t1.account_name account_name from t1 order by t1.account_id)

        union/union all

select * from

        (select t2.account_id account_id,t2.account_name account_name from t2 order by t2.account_id);

引申知识点:Union和Union All的区别

Union:对多结果集并集操作,不包括重复行,同时按默认规则排序;

Union All:对多结果集并集操作,包括重复行,不进行排序;

 

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值