class SyncAvergerStarToShixun < ActiveRecord::Migration[5.2] def change Shixun.find_each do |shixun| averge_star = Game.find_by_sql("select ifnull(sum(g.star),0)/ifnull(count(*),1) as averge_star from (games g left join (myshixuns m join shixuns s on s.id = m.shixun_id) on m.id = g.myshixun_id) where star != 0 and s.id = #{shixun.id}").first.try(:averge_star) averge_star = averge_star || 5 puts(averge_star) shixun.update_column(:averge_star, averge_star.round(1)) end end end