简体   繁体   English

我可以使此SQL查询更有效吗?

[英]Can I make this SQL query more efficient?

I have an SQL query which works fine, but I feel like there must be a more efficient way of writing it. 我有一个运行良好的SQL查询,但我觉得必须有一种更有效的编写方式。 By joining two tables A and B that contain coordinates, I am comparing distances (in metres) between each coordinate. 通过联接包含坐标的两个表A和B,我正在比较每个坐标之间的距离(以米为单位)。 I then sum/count the number of coordinates in table B that are within set distances of coordinates in table A and output the result: 然后,我对表B中的坐标数求和/计数,这些坐标在表A中的坐标设定距离之内,并输出结果:

select a.name,
       sum(case when ST_GeodesicLengthWGS84(ST_SetSRID(ST_LineString(a.lat, a.lon, b.lat, b.lon),4326)) < 10.0 then 1 else 0 end) 10mCount,
       sum(case when ST_GeodesicLengthWGS84(ST_SetSRID(ST_LineString(a.lat, a.lon, b.lat, b.lon),4326)) < 50.0 then 1 else 0 end) 50mCount,
       sum(case when ST_GeodesicLengthWGS84(ST_SetSRID(ST_LineString(a.lat, a.lon, b.lat, b.lon),4326)) < 1000.0 then 1 else 0 end) 1000mCount 
FROM a JOIN
     b
GROUP BY a.name
ORDER by 1000mCount desc
LIMIT 10;

I feel like there must be a way to call ST_GeodesicLengthWGS84(ST_SetSRID(ST_LineString(a.lat, a.lon, b.lat, b.lon), 4326)) once, get the result and then increment each 10m, 50m and 1000m count. 我觉得必须有一种方法可以调用ST_GeodesicLengthWGS84(ST_SetSRID(ST_LineString(a.lat, a.lon, b.lat, b.lon), 4326))一次,获取结果,然后分别递增10m,50m和1000m计数。

Any ideas? 有任何想法吗? Thanks. 谢谢。

Try prequerying, but your data is STILL requiring the results to go through EVERY RECORD. 尝试进行预查询,但是您的数据仍然需要结果通过每个记录。

select
      PreQuery.name,
      sum(case when PreQuery.Geode < 10.0 then 1 else 0 end) 10mCount,
      sum(case when PreQuery.Geode < 50.0 then 1 else 0 end) 50mCount,
      sum(case when PreQuery.Geode < 1000.0 then 1 else 0 end) 1000mCount 
   from
      ( select 
              a.name,
              ST_GeodesicLengthWGS84( ST_SetSRID( ST_LineString(a.lat, a.lon, b.lat, b.lon),4326)) as Geode
           from 
              a join b  
                 (YOU ARE MISSING the JOIN 'ON' clause... how related) ) PreQuery
   GROUP BY 
      PreQuery.name
   ORDER by 
      1000mCount desc
   LIMIT 10;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM