• 解决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

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

  • 相关阅读:
    mysql 表映射为java bean 手动生成。
    MySQL 存储修改
    jdk 8 日期处理。
    jsp jstl quote symbol expected
    spring boot 接口用例测试
    spring boot js 文件引用 单引问题。
    spring boot 自定义视图路径
    spring 事务回滚。
    Eclipse svn 项目 星号
    Codeforces Round #277.5 (Div. 2)-B. BerSU Ball
  • 原文地址:https://www.cnblogs.com/mark8080/p/8431419.html
Copyright © 2020-2023  润新知