翻译SQL查询到ActiveRecord (Rails)

时间:2021-07-17 09:50:37

I have encountered difficulties in translating SQL query to ActiveRecord performance. I would be grateful for their assistance!

我在将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;

1 个解决方案

#1


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

#1


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