一.先连接后排序
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:对多结果集并集操作,包括重复行,不进行排序;

本文深入探讨了在SQL查询中,连接排序与连接操作的先后顺序对最终结果的影响。首先,介绍了当排序操作在连接之前执行时,只有最后一个连接部分能拥有排序子句,并且只能通过列号或别名进行排序。接着,阐述了在连接之后执行排序的情况,即多个结果集在被union/unionall连接后仍保持原有排序,需要将结果集放入子查询中进行排序。文章还详细解释了Union和UnionAll的区别,帮助读者理解如何在不同场景下灵活运用这些操作符。
1806

被折叠的 条评论
为什么被折叠?



