Ruby On Rails retrieve mysql database data 'a' distinct 'b'

孤街浪徒 提交于 2019-12-11 22:13:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!