Rails嵌套SQL查询

gdi*_*azc 18 sql ruby-on-rails

我有一个数据库模型Position(lat,lon),其中包含latitudeslongitudes.

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

为此,我使用hasrsine_distance公式计算两个坐标之间的公里(在地球表面上)的距离(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
Run Code Online (Sandbox Code Playgroud)

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

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

SELECT * FROM ( SELECT * FROM Positions WHERE lat-latitude < some_reasonable_upper_bound AND lon-longitude < same_upper_bound ) WHERE costly_haversine_distance < tolerance
Run Code Online (Sandbox Code Playgroud)

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

非常感谢!

jdo*_*doe 28

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

LineItem.where(product_id: Product.where(price: 50))
Run Code Online (Sandbox Code Playgroud)

它提出以下要求:

SELECT "line_items".* FROM "line_items" 
WHERE "line_items"."product_id" IN 
(SELECT "products"."id" FROM "products" WHERE "products"."price" = 50)
Run Code Online (Sandbox Code Playgroud)

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