【问题标题】:HQL version of a SQL join with group by使用 group by 的 SQL 连接的 HQL 版本
【发布时间】:2011-03-25 01:46:21
【问题描述】:

我有两张桌子,Band 和 Votes。 Band 有一个名称和一个 id,Votes 有一个 total_votes 列和一个名为 band_id 的外键,指向 band.id。

我有很多选票,保存在不同的日期。我想要做的是找到每个波段的 total_votes 列的最大值。以下 SQL 查询有效:

select b.name,max(v.total_votes) as total from band b, votes v 
    where b.id=v.band_id
    group by b.name order by total desc;

不过,我正在使用的系统使用的是 Hibernate。我想将该 SQL 查询重写为 HQL 或 Hibernate 条件查询。

这很简单,我只是想念它吗?感谢您的帮助。

【问题讨论】:

    标签: java sql hibernate group-by hql


    【解决方案1】:

    在 HQL 中,你能试试这个吗:

    select band.name, max(vote.totalVotes)
    from Band band
         join band.votes vote
    group by band.name
    order by max(vote.totalVotes) desc
    

    这假设BandVotes 之间存在一对多关联(实际上,提供对象模型在使用 HQL 和/或 Criteria API 时非常有用,因为您正在查询对象模型) .

    以防万一,这里是文档的相关部分:

    14.12. The group by clause

    返回聚合值的查询 可以按 a 的任何属性分组 返回的类或组件:

    select cat.color, sum(cat.weight), count(cat)
    from Cat cat
    group by cat.color
    
    select foo.id, avg(name), max(name)
    from Foo foo join foo.names name
    group by foo.id
    

    have 子句也是允许的。

    select cat.color, sum(cat.weight), count(cat)
    from Cat cat
    group by cat.color
    having cat.color in (eg.Color.TABBY, eg.Color.BLACK)
    

    SQL 函数和聚合函数 被允许拥有和订购 条款,如果它们得到支持 底层数据库(即,不在 MySQL)。

    select cat
    from Cat cat
        join cat.kittens kitten
    group by cat.id, cat.name, cat.other, cat.properties
    having avg(kitten.weight) > 100
    order by count(kitten) asc, sum(kitten.weight) desc
    

    group by 子句和 order by 子句可以包含算术 表达式。 Hibernate 也没有 当前展开一个分组实体,所以 如果全部,您不能按猫分组 cat 的属性是非聚合的。 您必须列出所有未汇总的 明确的属性。

    【讨论】:

      猜你喜欢
      • 2011-02-07
      • 1970-01-01
      • 1970-01-01
      • 2021-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-17
      • 1970-01-01
      相关资源
      最近更新 更多