I am trying to calculate shortest distance from each point to polygon where idfield match and add the distance to a field in the point table:
For the two "A" points the distance is the same, which is incorrect. I understand why but not how to fix it. If I had only one A point, it would work.
update public.tbl2
SET dist = sub.dist
from (
select tbl2.idfield,
st_shortestline(tbl1.geom, tbl2.geom) geom,
round(st_length(st_shortestline(tbl1.geom, tbl2.geom))::numeric, 0) dist
from public.tbl1 , public.tbl2
where tbl1.idfield = tbl2.idfield
) sub
where sub.idfield = tbl2.idfield

UPDATEis effectively a per-row operation; you can refer to the updated row in the whole statement, and filter accordingly. Use this https://gis.stackexchange.com/questions/278357/how-to-update-with-lateral-nearest-neighbour-query/278362#278362 for performance, with an additionalWHEREfilter foridfieldin the sub-query, andST_Distancein theSELECT. – geozelot Mar 23 '21 at 08:39UPDATEstatements with direct relevance to your use case https://gis.stackexchange.com/questions/365070/update-points-geometry-while-snapping-them-to-nearest-line/365091#365091 – geozelot Mar 23 '21 at 09:09