2013-06-18 81 views
0

我有以下查詢。如何將以下查詢轉換爲HQL查詢。如何我可以將以下SQL查詢轉換爲HQL查詢

+--------+------------+-------+ 
| type | variety | price | 
+--------+------------+-------+ 
| apple | gala  | 2.79 | 
| apple | fuji  | 0.24 | 
| apple | limbertwig | 2.87 | 
| orange | valencia | 3.59 | 
| orange | navel  | 9.36 | 
| pear | bradford | 6.05 | 
| pear | bartlett | 2.14 | 
| cherry | bing  | 2.55 | 
| cherry | chelan  | 6.33 | 
+--------+------------+-------+ 

我希望得到以下結果

+--------+----------+-------+ 
| type | variety | price | 
+--------+----------+-------+ 
| apple | fuji  | 0.24 | 
| orange | valencia | 3.59 | 
| pear | bartlett | 2.14 | 
| cherry | bing  | 2.55 | 
+--------+----------+-------+ 

select f.type, f.variety, f.price 
from (
    select type, min(price) as minprice 
    from fruits group by type 
) as x inner join fruits as f on f.type = x.type and f.price = x.minprice; 

回答

0

我認爲這應該工作(未測試):

select f.type, f.variety, f.price 
from fruits f 
where f.price = (
    select min(f2.price) 
    from fruits f2 
    where f2.type = f.type 
) 

編輯:請記住,如果type有同一個price多於一個variety,比所有這些行將被選中與此查詢。

+0

我可以使用連接寫這個嗎 – PSR

+0

從文檔:* HQL子查詢只能出現在select或where子句中* http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html /queryhql.html#queryhql-subqueries – lunr

+0

但它給我的所有記錄。我只需要最高記錄 – PSR