Rails嵌套SQL查询

我有一个数据库模型Position(lat,lon) ,它拥有latitudeslongitudes.

我有一个名为show_close_by的控制器动作,它接收一个以度为单位的位置(my_lat, my_lon) ,一个公差(以公里为单位),并且应该返回数据库中位于公差范围内的位置列表。

为此,我使用hasrsine_distance公式计算两个坐标(lat1, lon1, lat2, lon2)之间的公里距离(在地球表面上(lat1, lon1, lat2, lon2)

为了使查询更快,我在查询中编写了整个haversine_distance公式:

 ... WHERE 2*6371*asin(sqrt( power( sin( (:lat2-latitude)*pi()/(180*2) ) ,2) + cos(latitude*pi()/180)*cos(:lat2*pi()/180)*power(sin( (:lon2-longitude)*pi()/(180*2) ),2) )) < tolerance 

查询的细节无关紧要。 我的疑问是:是否有必要为数据库中的每个位置计算这个巨大的函数? 我可以使用更简单的function过滤掉一些显然距离太远的位置吗?

好吧,我可以:使用嵌套的SQL查询,我可以在数据库中查询大“正方形”(在纬度/经度空间内)的位置,然后使用更昂贵的三角函数过滤那些位置。 类似于以下内容:

 SELECT * FROM ( SELECT * FROM Positions WHERE lat-latitude < some_reasonable_upper_bound AND lon-longitude < same_upper_bound ) WHERE costly_haversine_distance < tolerance 

最后,我的问题是:我如何在Rails中实现它(不自己编写整个查询)? Positions.where(reasonable_upper_bound).where(costly_but_accurate_restriction)进行嵌套查询? 如果没有,怎么样?

非常感谢!

以下是如何进行嵌套查询:

 LineItem.where(product_id: Product.where(price: 50)) 

它提出以下要求:

 SELECT "line_items".* FROM "line_items" WHERE "line_items"."product_id" IN (SELECT "products"."id" FROM "products" WHERE "products"."price" = 50) 

请注意, 只会products表中获取id 。 如果您尝试使用另一种方式连接两个实体并且这种魔法不合适,请使用Product.select(:some_field).where(...)