SQL Ruby on Rails:从数据库列中获取最大值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4974049/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ruby on Rails: getting the max value from a DB column
提问by keybored
Currently I can make the straight-up SQL query on my DB:
目前我可以在我的数据库上进行直接的 SQL 查询:
SELECT MAX(bar) FROM table_name
And it returns with the max value in that table. When I make what I consider to be an equivalent call in Rails, however, it does not work. I am calling:
它返回该表中的最大值。然而,当我在 Rails 中进行我认为是等效的调用时,它不起作用。我打电话:
Bar.all(:select => "Max(bar)")
This simply returns with:
这只是返回:
[#<Bar >]
In the column I'm calling on is a series of identifying numbers, I'm looking for the largest one. Is there some other way of accessing this in Rails?
在我要调用的列中是一系列识别数字,我正在寻找最大的一个。在 Rails 中还有其他方法可以访问它吗?
回答by Dylan Markow
Assuming your model name is Bar
and it has a column named bar
, this should work:
假设您的模型名称是Bar
并且它有一个名为 的列bar
,这应该可以工作:
Bar.maximum("bar")
See the excellent Rails Guides section on Calculationsfor more info.
有关更多信息,请参阅有关计算的优秀Rails 指南部分。
回答by Manish Kasera
one more way
另一种方式
Bar.select("Max(bar) as max_bar").first.max_bar