grails findAll with conditions或executeQuery

时间:2012-04-04 23:39:41

标签: mysql hibernate grails groovy subquery

我花了一些时间在这上面。我的问题涉及带回某些条件和条件的域对象:

我有一大套自行车。有可能有多个具有相似车轮尺寸的自行车。例如,我可以拥有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';

结果会给我带自行车的行: liner,larker和jefro

在grails // groovy中有相同的方法吗? (将 liner,larker和jefro 放入域对象列表中)

我尝试过使用像

这样的结构
def bikes = Bike.executeQuery(...)
or
def bike = Bike.findAll(...)

但我似乎无法执行与我制作的MySQL脚本具有类似结构的查询。

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

在MySQL中,您使用子查询来检索数据。使用GORM无法实现AFAIK。您可以做的是将其写在Hibernate Query Language (HQL)

假设您的域类名为Bike。

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])