ST_3DClosestPoint returning multiple points

2019-08-17 18:17发布

问题:

Data

I have 2 tables - 3D point geometries (obs.geom), n=10 - a single 3D point (target.geom), n=1

Problem - part 1

When I run the following code it lists all 10 of the obs geoms rather than just the closest point to the target.geom. Can anyone give me some pointers?

SELECT ST_3DClosestPoint(target.geom, obs.geom)
FROM target, obs

Part 2

I then want to add in the Distance3D

SELECT ST_3DDistance(ST_3DClosestPoint(target.geom, obs.geom) as dist_closest, obs.geom) as distance
FROM target, obs
where dist_closest > 1.5

回答1:

We cannot use knn operator(it works only with 2D) so we have to work around a bit. For a single point in the target table it will be like this.

select * , st_distance(o.geom, t.geom), st_3ddistance(o.geom, t.geom)
  from obs o, target t
 order by st_3ddistance(o.geom, t.geom) limit 1

But it will not work if you want results for many targets at once. If you want find closest points for many targets then we have to use lateral join

select t2.*, a.*
  from target t2,
  lateral (select o.*
             from obs o, target t
            where t2.id=t.id
            order by st_3ddistance(o.geom, t.geom) limit 1) a

If you want more then one closest point just increase the limit.