【问题标题】:UNION with order by in HQL在 HQL 中使用 order by 的 UNION
【发布时间】:2015-04-29 12:54:12
【问题描述】:

如何在HQL 中进行Mysql 查询:

select id , date from TABLE_1
union all
select id , date from TABLE_2

order by date asc

我知道union 的替代方法是发出两个单独的请求,但我想要unionorder by,因为它对我有很大帮助。

【问题讨论】:

    标签: mysql sql hibernate


    【解决方案1】:

    需要括号——你所拥有的是

    ( select id , date from TABLE_1 )
    union all
    ( select id , date from TABLE_2
    order by date asc )
    

    你想要的是

    ( select id , date from TABLE_1 )
    union all
    ( select id , date from TABLE_2 )
    order by date asc
    

    【讨论】:

    • 不,它在MySQL 中没有括号也可以工作,但我想要HQL 中的查询。
    【解决方案2】:

    您可以将separate 查询分成两个查询,然后将combine 将结果列表合并为一个,最后将sortComparator 合并为最终列表:

    Query query1 = session.createQuery("select t.id,t.dt from Table1 t");
    Query query2 = session.createQuery("select t.id,t.dt from Table2 t");
    
    List list1= query1.list();
    List list2= query2.list();
    
    list1.add(list2);
    
    
    Collections.sort(list1, new Comparator<TABLE>(){
           public int compare (Table t1, Table t2){
               return t1.getDate().compareTo(t2.getDate());
           }
    });
    

    编辑(在 cmets 之后):UNION 的情况下(当查询使用 UNION 而不是 union all 并且也没有 Order By)我们可以使用 HashSet:

    Query query1 = session.createQuery("select t.id,t.dt from Table1 t");
    Query query2 = session.createQuery("select t.id,t.dt from Table2 t");
    
    List list1= query1.list();
    List list2= query2.list();
    
    list1.add(list2);
    
    HashSet uniqueResult = new HashSet(list1);
    

    【讨论】:

    • 最后它可以在没有你的最后一行的情况下工作,因为list1 的排序很好,不需要将它们全部收集在HashSet 中,因为它失去了排序......你能编辑你的答案吗
    • 是的,当然,我只是在 unique result (UNION) 的情况下添加了它,对于 UNION ALL 它不需要使用 HashSet
    • 哦,是的,你是对的(我没有注意到哈希集可能会破坏顺序)所以让我编辑答案并删除最后一行。
    • 现在很好但是HashSet的使用必须在我认为的排序之前。
    • 这是针对特定解决方案的一种单独方法我的意思是,仅当 UNIQUE 很重要而 Order by 不重要时,才使用 HashSet,因为 HashSet 不保证任何排序并且不确定是否对 HashSet 进行排序基于特定字段的实体。和yes 它应该在排序之前(而不是它)
    猜你喜欢
    • 1970-01-01
    • 2014-05-30
    • 2010-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-01
    相关资源
    最近更新 更多