2011-03-01 25 views
1

在linq2nhibernate中使用'group by'出現很多問題之後,我嘗試切換到HQL,但是我正在用一個簡單的示例來構造它。HQL和分組

我有如下表(ForumThreadRatings):

Group by

我想獲取收視率最高的論壇主題的列表,這意味着我需要做的正柱和一個總和由forumthread組。我已經嘗試了一個例子,是想通過在HQL做一個簡單的組沒有運氣:

select ftr.ForumThread from ForumThreadRating ftr group by ftr.ForumThread 

但我收到以下錯誤:

Column 'ForumThreads.Id' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. 

什麼可能我會丟失?

回答

2

the docs

NHibernate currently does not expand a grouped entity, so you can't write group by cat if all properties of cat are non-aggregated. You have to list all non-aggregated properties explicitly.

在任何情況下,準確的查詢可以通過以下方式實現:

select distinct ftr.ForumThread from ForumThreadRating ftr 

但是,當然,你可能需要sumcount的東西,所以你需要明確地聚合這些屬性。


更新:這裏是如何獲得前10個線程:

var topThreads = session.CreateQuery(@" 
       select (select sum(case 
             when rating.Positive = true then 1 
             else -1 
            end) 
         from ForumThreadRating rating 
         where rating.ForumThread = thread), 
         thread 
       from ForumThread thread 
       order by 1 desc 
       ") 
       .SetMaxResults(10) 
       .List<object[]>() 

正如你可以看到,該查詢返回的object[]列表,且每兩個要素:[0]是評級和[1]是ForumThread。

可以使用得到公正的ForumThreads:

.Select(x => (ForumThread)x[1]); 

或將其投射到一個DTO等

+0

謝謝,我有試過「由ForumThreadRating FTR組選擇ftr.ForumThread.Id ftr.ForumThread「返回的ID列表,但我怎樣才能檢索在同一個查詢中的對象?我一直在尋找類似於sql的選擇「Select ForumThreads where Id in(select id ...)」,地址是http://docs.jboss.org/hibernate/core/3.3/reference/en/html/queryhql。 HTML,但無法找到一種方法來做到這一點? – Dofs

+0

@Dofs:你想運行的* actual *查詢是什麼?即你的結果是什麼? –

+0

Hi Diegeo Mijelshon,我想檢索排名前10的論壇主題列表,按評級排序。每個評分都有一個條目,可以是正面的也可以是負面的(如SO),所以排序應該是特定主題的正面評分減去負面評分的總和。 – Dofs