Ruby on Rails中嵌套查询的问题

时间:2015-04-17 15:30:31

标签: mysql ruby-on-rails ruby

我有三个模型FieldFlightFieldBoundaryDetailField有许多Flights,其中有一个FieldBoundaryDetail

基本上,我希望最后一次航班获得FieldFieldBoundaryDetail

我用SQL编写了它。为了排序和搜索目的,我需要它是一个Rails ActiveRecordRelation,但我很难将其转换为Rails。

SELECT *
FROM fields
LEFT JOIN (SELECT * 
           FROM (SELECT * 
                 FROM flights
                 ORDER BY event_date DESC) AS flight
           GROUP BY flight.field_id
          ) AS flight ON fields.id = flight.field_id
INNER JOIN field_boundary_details ON fields.id = field_boundary_details.field_id

2 个答案:

答案 0 :(得分:0)

作为一个简单的答案,您可以将find_by_sql与您的查询一起使用,稍加修改:

Fields.find_by_sql "SELECT fields.*
                    FROM fields
                    LEFT JOIN (SELECT * 
                               FROM (SELECT * 
                                     FROM flights
                                     ORDER BY event_date DESC) AS flight
                               GROUP BY flight.field_id
                              ) AS flight ON fields.id = flight.field_id
                    INNER JOIN field_boundary_details ON fields.id = field_boundary_details.field_id"

答案 1 :(得分:0)

我有一个解决方案,但它不是很优雅。希望有人能给出更好的答案。

latest_flight_ids = Field.latest_flight_for_each_field.map {|flight| flight.id.to_s}.join(",")
Field.select("*").
     joins("LEFT JOIN flights on fields.id = flights.field_id").
     joins(:field_boundary_detail).
     where("flights.id IN(#{latest_flight_ids}) OR flights.id IS NULL")