簡體   English   中英

具有group by的SQL連接的HQL版本

[英]HQL version of a SQL join with group by

我有兩張桌子,樂隊和投票。 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的所有屬性都是非聚合的,則不能逐個編寫。 您必須明確列出所有非聚合屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM