2

我正在使用 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

休眠抱怨: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

我应该如何解决这个问题?

4

1 回答 1

1

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

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

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

第三:如果你使用UNION ALL,为什么还要使用DISTINCT??使用 UNION 而不使用 ALL 与 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
于 2013-09-04T11:03:34.343 回答