【发布时间】:2015-06-28 21:01:38
【问题描述】:
获取最后一条记录在 SQL 中是微不足道的,例如(对于 MySQL)
class ExchangeRate {
Currency from
Currency to
BigDecimal rate // e.g. 10
Date dateCreated
}
class Currency {
String iso
etc..
}
获取最新的 SQL 很简单:
Select max(id), rate
from exchange_rate
where from_id = 1
and to_id = 3
或
select rate
from exchange_rate
where from_id = 2
order by id desc
limit 1
问题是,如何在 Grails 中有效地做到这一点?我只想要一个结果。
这显然行不通:
def query = ExchangeRate.where {
from == from && to == to && id == max(id)
}
ExchangeRate exchangeRate = query.find()
已经有几篇关于这个的帖子,但没有一个我可以弄清楚如何应用的实际答案(我是一个 SQL 人,并且不知道休眠语言,并且希望一个不涉及它的解决方案有一个)
如果有一种简单的方法可以直接运行 SQL,而无需手动管理可行的结果集(因为我们永远不会使用 MySQL 以外的其他数据库)
我确信它可以通过排序和限制来完成,但是 a) 没有找到我可以复制的示例,并且 b) 会假设这是低效的,因为似乎排序和限制是在代码中完成的,不是 SQL?
此示例在文档中:
Book.findAll("from Book as b where b.author=:author",
[author: 'Dan Brown'], [max: 10, offset: 5])
可能会导致:
def exchangeRates = ExchangeRate.findAll("from ExchangeRate as e where e.from = :from order by id desc", [from: from], [max: 1])
if (exchangeRates.size() == 1) {
return exchangeRates.first().rate
}
return null
有没有更好的方法(例如,一种不使用 hibernate 低级语言的方法,或者一种使用 SQL 的方法,或者一种更有效的方法?)
【问题讨论】:
-
有几种解决方案:这个相关问题应该会给你一些答案:stackoverflow.com/questions/12783318/…
标签: grails