How to get the latest record from each group in ActiveRecord?

后端 未结 5 1993
暖寄归人
暖寄归人 2020-12-14 01:07

In my Ruby on Rails application I have a database structure like this:

Project.create(:group => \"1\", :date => \"2014-01-01\")
Project.create(:group =         


        
5条回答
  •  眼角桃花
    2020-12-14 01:22

    Postgres

    In Postgres, this can be achieved with the following query.

    SELECT DISTINCT ON ("group") * FROM projects
    ORDER BY "group", date DESC, id DESC
    

    Because the date column might not be unique here, I have added an additional ORDER BY clause on id DESC to break ties in favor of the record with the higher ID, in case two records in a group have the same date. You might instead want to use another column like the date/time of the last update or so, that depends on your use case.

    Moving on, ActiveRecord unfortunately has no API for DISTINCT ON, but we can still use plain SQL with select:

    Project.select('DISTINCT ON ("group") *').order(:group, date: :desc, id: :desc)
    

    or if you prefer using ARel instead of having raw SQL:

    p = Project.arel_table
    Project.find_by_sql(
      p.project(p[Arel.star])
       .distinct_on(p[:group])
       .order(p[:group], p[:date].desc, p[:id].desc)
    )
    

    MySQL

    For other databases like MySQL this is unfortunately not as convenient. There are a variety of solutions available, see for example this answer.

提交回复
热议问题