简体   繁体   中英

SQL equivalent to an active record query

I have a query I have made that works well

Team.all.map do |team|
   message = CoachFee.find_one(team_id: team.id).team_price_explanation[:prices]
end

My 'team' class is simply

{
         :id => 1,
    :team_id => 6,
 :created_at => nil,
  :player_id => nil,
 :updated_at => nil,
    :user_id => 1417
}

The team class has a one to many relationship with the CoachFee class.

The only problem is that I have well over 300,000 database values of CoachFee in my application, and so running this can take forever. (well over 4 minutes).

Are there any sql gurus out there that know quickly how to replace CoachFee.find_one(team_id: team.id) from Active Record to SQL?

Much thanks to anyone in advance!

Give this a try:

CoachFee
  .where(id: CoachFee.select(CoachFee.arel_table[:id].minimum).group(:team_id))
  .map {|cf| cf.team_price_explanation[:prices]} 

This will result in the following SQL

SELECT 
  coach_fees.*
FROM 
  coach_fees 
WHERE 
  coach_fees.id IN ( 
    SELECT 
      MIN(coach_fees.id) 
    FROM 
      coach_fees
    GROUP BY 
      coach_fees.team_id
  )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM