【问题标题】:grails findAll with conditions or executeQuery带有条件的 grails findAll 或 executeQuery
【发布时间】:2012-04-18 17:33:16
【问题描述】:

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

我有很多自行车。有可能拥有多辆车轮尺寸相似的自行车。例如我可以有 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 脚本结构相似的查询。

感谢您的帮助!

【问题讨论】:

    标签: mysql hibernate grails groovy subquery


    【解决方案1】:

    在您的 MySQL 中,您使用子查询来检索数据。 AFAIK 这对于 GORM 是不可能的。你可以做的是写在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])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多