Fetching Minimum/Maximum for each group in ActiveRecord

前端 未结 5 1277
说谎
说谎 2021-02-05 20:53

This is an age-old question where given a table with attributes \'type\', \'variety\' and \'price\', that you fetch the record with the minimum price for each type there is.

5条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-05 21:42

    I've been fighting with this for a while and for the moment it seems that you are pretty much stuck with generating SQL.

    However, I have a couple refinements to offer.

    Instead of find_by_sql, as @François suggested, I've used ActiveRecord's to_sql and joins to "guide" my SQL a little bit:

    subquery_sql = Table.select(["MIN(price) as price", :type]).group(:type).to_sql
    joins_sql    = "INNER JOIN (#{subquery_sql}) as S
                    ON table.type = S.type
                    AND table.price = S.price"
    
    Table.joins(joins_sql).where().order()
    

    As you can see, I'm still using raw SQL, but at least it's only on the part where AR gives no support (AFAIK ActiveRecord simply can't manage INNER JOIN ... ON ...) and not on the whole thing.

    Using joins instead of find_by_sql makes the query chainable - you can add extra conditions, or sort the table, or put everything in a scope.

提交回复
热议问题