zoukankan      html  css  js  c++  java
  • 解决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

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

  • 相关阅读:
    IOS-在ARC项目中使用非ARC框架或者类库
    IOS-Social.framework
    IOS- 单例
    IOS-二维码的实现
    IOS-JSON & XML解析
    SCOI2011 地板 (BZOJ2331)
    Formula 1(URAL1519)
    Tour in the Castle(ZOJ3256 矩阵加速插头dp)
    Tony's tour(poj1739,男人题之一,插头dp)
    POJ3133(插头dp)
  • 原文地址:https://www.cnblogs.com/mark8080/p/8431419.html
Copyright © 2011-2022 走看看