带有group by的SQL连接的HQL版本

我有两张桌子,乐队和投票。 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条件查询。

这很容易,我只是错过了吗? 谢谢你的帮助。

在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。 group by子句

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

 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 

还允许使用having子句。

 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) 

如果底层数据库(即不在MySQL中)支持,则在having和order by子句中允许使用SQL函数和聚合函数。

 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的所有属性都是非聚合的,则不能逐个编写。 您必须明确列出所有非聚合属性。