I am using postgis to calculate the distance between every ‘a’ and its corresponding ‘b’ type point.
So far I have managed to do this with this query:
SELECT a.name, min(ST_Distance(a.the_geom, b.the_geom)) as distance
FROM a, b
GROUP BY a.name;
This works, it however only lists the name of the a type point and the distance to its closest b type point, it doesn’t list the name of the closest b type point to each a type point as I’d like it to do.
I would usually do this by joining both tables but they are unrelated and share no keys so I wouldn’t know how to join them.
The brute force approach (assuming that PostGIS supports WITH clauses, and assuming I have the syntax of WITH clauses correct – both unchecked assumptions):
This generates the list of names (
a_nameandb_name) plus the corresponding distance using a Cartesian product (which is what your original query does before the GROUP BY kicks in). It then selects the two names and the distance from the join of that table with the same table grouped over thea_nameand joined on thea_nameand the minimum distance.Clearly, if WITH is not supported, you can write the WITH clause out twice and hope your optimizer is good.