如何选择rails中具有最低字段值的记录

时间:2021-02-14 09:17:45

In my rails app i fetch some data, it's result could be null, one, or more identical records but with different price value, so i need to iterate in array and select record (array value) with lowest value of price. How can i do this? I ave such code part:

在我的rails应用程序中我获取一些数据,它的结果可能是null,一个或多个相同的记录但具有不同的价格值,所以我需要迭代数组并选择具有最低价格值的记录(数组值)。我怎样才能做到这一点?我有这样的代码部分:

@prlist = PriceList.find(:first, :conditions => { :id => @search.map(&:price_list_id)})

for example:

id name value
1 ololo 15
2 ololo 14
3 ololo 26

i need to select 2-d.

我需要选择2-d。

2 个解决方案

#1


1  

Just add order by 'value':

只需按'值'添加订单:

@prlist = PriceList.find(:first, :conditions => { :id => @search.map(&:price_list_id)}, :order => 'value')

#2


2  

I believe that

我相信

PriceList.where('value = MIN(value)')

should work for you (at least for MySQL, Postgres and SQLite3 ).

应该适合你(至少对于MySQL,Postgres和SQLite3)。

If you only need the minimum value (not the entire row):

如果您只需要最小值(不是整行):

PriceList.minimum('value')

#1


1  

Just add order by 'value':

只需按'值'添加订单:

@prlist = PriceList.find(:first, :conditions => { :id => @search.map(&:price_list_id)}, :order => 'value')

#2


2  

I believe that

我相信

PriceList.where('value = MIN(value)')

should work for you (at least for MySQL, Postgres and SQLite3 ).

应该适合你(至少对于MySQL,Postgres和SQLite3)。

If you only need the minimum value (not the entire row):

如果您只需要最小值(不是整行):

PriceList.minimum('value')