我在将SQL查询转换为ActiveRecord性能方面遇到了困难。我很感激他们的帮助!
SELECT MAX(distances.max) from
(SELECT max(distance)
FROM
(SELECT * from tracks WHERE car_id=1) t , locations l
WHERE t.id=l.track_id
GROUP BY track_id) distances;
答案 0 :(得分:0)
def max_track_length
sql= Location.select("MAX(distance) as distance")
.joins("INNER JOIN tracks ON tracks.id=locations.track_id")
.where("tracks.car_id = ?", self.id).group(:track_id).to_sql
res=Car.from("(#{sql}) l").maximum("l.distance")
res||=0;
end