问题
My database have a device reading list,
columns are id ,device_id ,device_reading ,update_time
How can I select all latest reading for each device?
that means,I need sort data according to update_time first
then I need to filter database use some unique method(unique device_id)
then the I can retrieve device_reading from rows filtered just now.
That is to say, retrieve column a from table where b is distinct
how can I achieve this? in ruby on rails
thanks in advance
回答1:
Supposing that model name is DeviceReading
DeviceReading.distinct(:device_id).order('update_time DESC').pluck(:device_reading)
You can use ASC
in place of DESC
if you want to sort by ascending order
Source: Distinct and pluck sort/order
EDIT: The distinct only works in rails 4 so if you are using rails 3 you should do something like this:
DeviceReading.select(:device_id).uniq.pluck(:device_reading)
However when I chain .order('update_time DESC')
in above I get mysterious error. I am trying to find solution. meanwhile I Hope this helps you.
Source: distinct undefined error
回答2:
This questions looks quite similar to the one below:
Select first row in each GROUP BY group?
In the case when no elegant solution can be found the Rails way, you can first figure out the correct sql and use find_by_sql
to retrieve the dataset.
来源:https://stackoverflow.com/questions/25598614/ruby-on-rails-retrieve-mysql-database-data-a-distinct-b