简体   繁体   中英

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. By joining two tables A and B that contain coordinates, I am comparing distances (in metres) between each coordinate. 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:

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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