我正在尝试将一条“原始”的PostGIS SQL查询转换为Rails ActiveRecord查询。我的目标是将两个连续的ActiveRecord查询(每个查询大约需要1毫秒)转换为一个单独的ActiveRecord查询(需要1毫秒)。使用下面的SQL和
因此,我的直接请求是帮助我将这个查询转换为ActiveRecord查询(以及执行它的最佳方法)。
ActiveRecord::Base.connection.execute
,我能够验证时间减少。因此,我的直接请求是帮助我将这个查询转换为ActiveRecord查询(以及执行它的最佳方法)。
SELECT COUNT(*)
FROM "users"
INNER JOIN (
SELECT "centroid"
FROM "zip_caches"
WHERE "zip_caches"."postalcode" = '<postalcode>'
) AS "sub" ON ST_Intersects("users"."vendor_coverage", "sub"."centroid")
WHERE "users"."active" = 1;
注意,在此查询中,值<postalcode>
是唯一的可变数据。显然,这里有两个模型User
和ZipCache
。User
与ZipCache
没有直接关系。
当前的两步ActiveRecord查询如下。
zip = ZipCache.select(:centroid).where(postalcode: '<postalcode>').limit(1).first
User.where{st_intersects(vendor_coverage, zip.centroid)}.count