SQL选择不同的实体 - union all - 按另一个实体的列排序

时间:2013-09-04 09:25:23

标签: sql hibernate sql-order-by distinct union

我使用SQL访问实体(Forslag),但也希望使用其他实体的列(b.dato)进行排序。

这是我最初的SQL:

        select distinct ff.*
        from Forslag ff 
          inner join Forlag f on ff.forlag_id = f.forlag_id
          inner join LoggBehandling b on ff.forlag_id = b.forlag_id
          inner join Kontrollpanel p on f.uhrPuMote_id = p.saksbehandlerUhrPuMote_id
        where b.status_id = 7

        union all

        select distinct ft.*
        from Forslag ft
          inner join Tidsskrift t on ft.tidsskrift_id = t.tidsskrift_id
          inner join LoggBehandling b on ft.tidsskrift_id = b.tidsskrift_id
          inner join Kontrollpanel p on t.uhrPuMote_id = p.saksbehandlerUhrPuMote_id
        where  b.status_id = 7

        order by b.dato desc

Hibernate抱怨:ORDER BY items must appear in the select list if the statement contains a UNION, INTERSECT or EXCEPT operator.

我怀疑我无法真正添加b.dato来进行选择,因为我认为这会对映射产生影响:

        select distinct ff.*, b.dato
        from Forslag ff 
          inner join Forlag f on ff.forlag_id = f.forlag_id
          inner join LoggBehandling b on ff.forlag_id = b.forlag_id
          inner join Kontrollpanel p on f.uhrPuMote_id = p.saksbehandlerUhrPuMote_id
        where b.status_id = 7

        union all

        select distinct ft.*, b.dato
        from Forslag ft
          inner join Tidsskrift t on ft.tidsskrift_id = t.tidsskrift_id
          inner join LoggBehandling b on ft.tidsskrift_id = b.tidsskrift_id
          inner join Kontrollpanel p on t.uhrPuMote_id = p.saksbehandlerUhrPuMote_id
        where  b.status_id = 7

        order by b.dato desc

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

你确定是HQL而不是SQL ???

第一种:在HQL中使用UNION ALL是不可能的,但你必须执行两个不同的查询。

第二种:在SQL中,当您使用UNION操作时使用订单时,必须以这种方式将ORDER BY应用于结果表:

第三个:如果使用UNION ALL,为什么要使用DISTINCT?使用没有ALL的UNION与DISTINCT相同。

   select *
   from (
    select ff.*, b.dato as dato
    from Forslag ff 
      inner join Forlag f on ff.forlag_id = f.forlag_id
      inner join LoggBehandling b on ff.forlag_id = b.forlag_id
      inner join Kontrollpanel p on f.uhrPuMote_id = p.saksbehandlerUhrPuMote_id
    where b.status_id = 7

    union all

    select distinct ft.*, b.dato
    from Forslag ft
      inner join Tidsskrift t on ft.tidsskrift_id = t.tidsskrift_id
      inner join LoggBehandling b on ft.tidsskrift_id = b.tidsskrift_id
      inner join Kontrollpanel p on t.uhrPuMote_id = p.saksbehandlerUhrPuMote_id
    where  b.status_id = 7
  ) as resultTable
  order by resultTable.dato desc