解决UNION ALL合并两个结果集后排序的问题

日常开发中,如果实用UNION ALL合并两个已经排好序的结果集的时候,需求是第二个结果集数据排在第一个结果集数据下面,单纯的实用order by是无效的,因为order by的优先级比UNION ALL低。

例如:

select one.*  from (select t1.* from table1 t1 where 1=1 and t1.day >3 order by t1.create_date desc)  one 

UNION ALL

select two.*  from (select t2.* from table2 t2 where 1=1 and t1.day <=3 order by t2.create_date desc)  two

此时查询结果并不是安好two排序好之后  排在  one下面,如果要实现这样的需求,可以使用一个临时字段作为排序字段,该字段的作用是使合并后的结果集有一个统一的排序字段,合并前的结果集分别给默认值1和2,这样在合并后的结果集可以排序了.

select all.* from (select one.*  from (select t1.*,'1' as 'sortBy' from table1 t1 where 1=1 and t1.day >3 order by t1.create_date desc)  one 

UNION ALL

select two.*  from (select t2.* ,'2'  as  'sortBy' from table2 t2 where 1=1  and t.2day <=3 order by t2.create_date desc)  two) all where 1=1 order by all.sortBy asc

解决方案的巧妙之处就是,利用一个自定义的字段实现两个结果集的合并后排序。

posted @ 2018-02-08 14:37  美材帮  阅读(2574)  评论(0编辑  收藏  举报