2012-04-04 32 views
1

我一直在這方面花費一些時間。我的問題涉及帶回特定條件和條件的域對象:grails findAll with conditions或executeQuery

我有一大套自行車。有可能有多個類似車輪大小的自行車。例如,我可以有5輛自行車:

owner_id | bike | wheel | price | active | toolset | forLance 
_________|______|_______|_______|________|_________|__________ 
15459 |liner | 12 | 100 |  Y | null | H  
15459 |larker| 15 | 150 |  Y | null | H  
15459 |jefro | 21 | 225 |  Y | null | H  
15459 |raz | 21 | 230 |  Y | null | L  
15459 |jynx | 21 | 295 |  Y | null | P  

我下面的查詢檢索的所有非重複的輪轂尺寸,價格最低的自行車。

MySQL查詢:

select * from bike b 
where b.owner_id = 15459 
and not exists(select * from bike 
where wheels = b.wheels AND price < b.price 
and owner_id = b.owner_id) and b.active = 'Y'; 

結果會給我的自行車行:襯墊,larker和jefro

有沒有在grails // groovy中做到這一點的等價方法? (獲取襯墊,larker和jefro到域對象的列表)

我一直在使用的結構類似的嘗試:

def bikes = Bike.executeQuery(...) 
or 
def bike = Bike.findAll(...) 

但我似乎不能用類似的結構執行查詢MySQL腳本我做的。

感謝您的幫助!

回答

2

在你的MySQL中你使用子查詢來檢索數據。 AFAIK這對GORM來說是不可能的。你可以做的是寫在Hibernate Query Language (HQL)

讓我們假設你的域類被稱爲自行車。

Bike.findAll("from Bike as b where b.active = 'Y' and b.owner = :owner and b.id in elements(select b1.id from Bike where b1.owner = :owner and b1.active = 'Y' and b1.price < b.price)", ['owner':owner])