【问题标题】:Hibernate Distinct with order byHibernate Distinct with order by
【发布时间】:2016-03-10 11:12:11
【问题描述】:

谁能告诉我如何在 HQL 查询中使用 distinct 和 order by。 我一直在寻找解决方案,但似乎找不到确切的解决方案。


这是我的 HQL 查询

select distinct city 
from City city 
  where city.id is not null 
    and upper(city.name) != upper('Unknown')  
    and city.state.id =:stateId 
order by upper(trim(city.name))

问题 - SELECT DISTINCT、ORDER BY 表达式必须出现在选择列表中。

【问题讨论】:

  • 你为什么有两个订单?
  • 哦对不起,我刚刚粘贴了错误的查询,让我先更正一下。
  • 我不是休眠专家,但select city from City city 不会从表city 返回所有 列?在这种情况下, distinct 没有意义,因为 PK 列将成为结果的一部分。

标签: java hibernate postgresql


【解决方案1】:

按不属于所选distinct 列的列进行排序是没有意义的。

由于您没有加入集合,因此您的记录无论如何都会不同(至少 PK 会有所不同),您可以省略 distinct:

select distinct city 
from City city 
  where city.id is not null 
    and upper(city.name) != upper('Unknown')  
    and city.state.id =:stateId 
order by upper(trim(city.name))

一般来说,当结果集中确实有重复项,想要消除它们时,可以通过子查询来实现:

select city
from City city
  where city.id in (select c.id from City c join c.someCollection sc where ...)
order by upper(trim(city.name))

这种方法的另一个好处是它可能在性能方面更好,因为distincting 行在数据库中通常是一项昂贵的操作。

【讨论】:

  • 我的查询中不需要不同的关键字,所以我刚刚删除了它,现在它对我有用。感谢 a_horse 和感谢 Dragan,您的解决方案可能对其他人有所帮助。
  • 当然,按不属于所选不同列的列排序是有意义的。假设您有一个实体,将其命名为 Account,它封装了一个相关的子对象 Client,并且您希望按 Client.name 对 Accounts 进行排序,但不想将 Client.name 作为结果集中的字段返回,您只需要帐户字段,并说您的查询可能会返回重复项,在这种情况下您可能希望使用 distinct。
【解决方案2】:

使用此查询。 order by 不会加倍。你必须单独使用它。希望对你有帮助。

order by city.name 这意味着它将使用城市名称升序。

select distinct city.name, city.id
from City city 
where city.id is not null 
and upper(city.name) != upper('Unknown') 
and city.state.id =:stateId 
order by upper(trim(city.name))

【讨论】:

  • 我需要表格中的所有列。
  • 是的 Sky,我们可以通过在 select 中提及所有列来使用此查询,但我认为这不是一个好方法,我不想提及所有这些列。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-10
  • 1970-01-01
  • 2021-02-10
  • 1970-01-01
相关资源
最近更新 更多