I have a working SELECT statement but as SQL isn’t my strong point I don’t know how to make this into an UPDATE function. I have others that work but it appears to be JOIN’s getting me here.
I’ve tried a few ways I could think of:
UPDATE ptp_links SET geom = ST_MAKELINE (this results in every record getting the same line)
UPDATE FROM SELECT (this one gets me the close but throws an error about column "geom" is of type geometry but expression is of type record)
This is my SELECT Query:
SELECT
ST_MAKELINE(
ST_POINT(out_bs.longitude::DOUBLE PRECISION, out_bs.latitude::DOUBLE PRECISION, 4326),
ST_POINT(CASE WHEN ptp.link_purpose = 'backhaul'
THEN in_bs.longitude::DOUBLE PRECISION
ELSE ptp.in_address_geo_x::DOUBLE PRECISION
END,
CASE WHEN ptp.link_purpose = 'backhaul'
THEN in_bs.latitude::DOUBLE PRECISION
ELSE ptp.in_address_geo_y::DOUBLE PRECISION
END, 4326)
)
FROM ptp_links ptp
LEFT JOIN base_stations in_bs ON ptp.in_base_station = in_bs.id
LEFT JOIN base_stations out_bs ON ptp.out_base_Station = out_bs.id;
What I want to do is write the generated line from ST_MAKELINE back to the ptp_links table into the column called geom if anyone knows how I would do this in PostGIS.
2
Answers
You can lean on implicit joins in a standard
update..from..where
:Demo:
If you also grab some unique identifier from
ptp_links
, you can wrap yourselect
in awith
CTE and use it as a source for theupdate
statement: demoAnother way to wrap your base query is by making it a scalar subquery fed directly to the
update...set geom=
assignment: demoNote that in the last two cases you need to direct the incoming value to the target row by comparing a unique identifier. As reminded by @Bergi, if you don’t have one, there’s always the "hidden"
ctid
column you can use. Just keep in mind thatctid
is stable throughout a single query but it’s not guaranteed to stay consistent between separate, even consecutive queries.Apart from the approach shown by @Zegarek, you can first rewrite your query to use subqueries instead of (left) joins:
Now it’s easy to convert that into an
UPDATE
statement: