2011-04-07 84 views
1


這是一個奇怪的...
我有一個HQL查詢,忽略GOUP BY如果包括ORDER BY
它將被沒有組進行查詢,
但如果我通過
刪除爲了它會正常工作休眠 - 不能使用GROUP BY和ORDER BY一起

list = getSession().createQuery(
     "SELECT 
    Brand.name as Brand_name 
, Brand.url as Brand_url 
, Brand.email as Brand_email 
, Brand.brandId as Brand_brandId 
, Brand.description as Brand_description 
FROM com.affiliates.hibernate.Brand Brand 
INNER JOIN Brand.users as users 
WHERE 1=1 
AND users.userId>'0' 
order by Brand.email ASC 
group by brandId"//this one will be ignored because of the order by 
    ).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list(); 

SQL生成:

select 
     brand0_.NAME as col_0_0_, 
     brand0_.URL as col_1_0_, 
     brand0_.EMAIL as col_2_0_, 
     brand0_.DESCRIPTION as col_3_0_ 
    from 
     BRAND brand0_ 
    inner join 
     USERS_BRANDS users1_ 
      on brand0_.BRAND_ID=users1_.BRAND_ID 
    inner join 
     USER user2_ 
      on users1_.USER_ID=user2_.USER_ID 
    where 
     1=1 
     and user2_.USER_ID>'0' 
    order by 
     brand0_.EMAIL ASC limit ?  
+0

什麼是由Hibernate生成的SQL? – 2011-04-07 19:49:32

+0

補充說明,沒有組通過 – fatnjazzy 2011-04-07 20:01:16

+0

我會先做羣組。儘管如此,我認爲這不重要。 – extraneon 2011-04-07 20:09:10

回答

1

首先,請注意BRAND.BRAND_ID已從SQL中的列投影中刪除。這可能與該組相關,也可能因此而丟失。

其次,請注意查詢中沒有定義聚合函數。小組僅適用於聚合。嘗試向所有列添加聚合函數,例如max。這可能是問題

最後,嘗試完全在HQL資格brandId以消除任何混亂的原因:

group by Brand.brandId 
+0

謝謝,如此明顯,我必須休息一下! – fatnjazzy 2011-04-08 05:37:05

0

你應該GROUPBY後應用排序依據,但你已經寫成

order by Brand.email ASC 
group by brandId"//this one will be ignored because of the order by 
    ).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list(); 

但更改爲:

group by brandId"//this one will be ignored because of the order by 
    ).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list(); 
    order by Brand.email ASC 

然後它會工作