如何使用 Rails 3.0 将表与包含聚合函数的子查询连接起来
我有一个表 StockPrice,其中包含时间戳(时间)、股票代码(符号)和一些其他属性 a、b、c 等
在 SQL 中我会编写以下内容:
Select *
FROM stock_prices, (SELECT symbol, max(time) as max_time
FROM stock_prices
GROUP BY symbol) latest_prices
WHERE stock_prices.symbol = latest_prices.symbol
AND stock_prices.time = latest_prices.max_time
我想使用 Rails 3.0 ActiveRecord 查询内容来表达此查询选择、从、组等。我该怎么做?
I have a table StockPrice which contains a timestamp (time), a ticker symbol (symbol) and some other attributes a,b,c etc
In SQL I would write the following:
Select *
FROM stock_prices, (SELECT symbol, max(time) as max_time
FROM stock_prices
GROUP BY symbol) latest_prices
WHERE stock_prices.symbol = latest_prices.symbol
AND stock_prices.time = latest_prices.max_time
I want to express this query using the rails 3.0 ActiveRecord Query stuff select, from, group etc. How do I do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
虽然可以使用 Rails 方法和 SQL 片段的混合来完成此操作,但这可能会变得混乱。直接执行这样的复杂查询通常要简单得多。
看一下
find_by_sql
方法,在模型上下文中执行此操作:http://api.rubyonrails.org/classes/ActiveRecord/Base .html#method-c-find_by_sql
While it is possible to do this with a mixture of Rails methods and SQL fragments, this can get messy. It is often much simpler to execute complex queries such as this directly.
Take a look at the
find_by_sql
method to do this within the context of your model:http://api.rubyonrails.org/classes/ActiveRecord/Base.html#method-c-find_by_sql