Reputation: 468
Working with postgresql and postgis I have 2 openstreetmap tables, containing:
Now, I'm trying to loop through the Point table and for each record I'm trying to do some computations with postgis functions, e.g. ST_Intersects()
. Then trying to insert the results into another tables.
So far I've only done simple SELECT
queries with postgis functions, they basically work like this:
SELECT a.name, b.name
FROM table_point AS a, table_polygon AS b
WHERE a.name = 'Berlin' AND ST_Intersects(a.way, b.way);
Note: way
is the column in both tables containing geometry data.
Coming back to the loop I want to operate, I find myself with lacking plpgsql basics. I've created the following loop structure, but don't know how to select a second set of records (table_point AS a, table_polygon AS b
) for the postgis function.
Short: How to select the records for table_polygon
along with that FOR-loop?
Or, is there a better way to solve this?
DO
$do$
DECLARE
r RECORD;
BEGIN
FOR r IN SELECT * FROM table_point
LOOP
RAISE NOTICE '%', r;
...
END LOOP;
END;
$do$ LANGUAGE plpgsql
Using PGSQL 9.3.5 on Ubuntu 14.04 64-bit.
Upvotes: 1
Views: 5732
Reputation: 656882
You are thinking procedurally, while for most cases a set-based approach is superior in relational databases. Like:
INSERT INTO table_other (point, polygon, result)
SELECT a.name, b.name, calculate(a.?, b.?) AS result -- undefined what to do
FROM table_point a
JOIN table_polygon b ON ST_Intersects(a.way, b.way)
WHERE a.name = 'Berlin';
Upvotes: 2
Reputation: 5962
Just define r2 as a record..
then do something like:
FOR r IN SELECT * FROM table_point
LOOP
RAISE NOTICE '%', r;
for r2 in select * from table2 where table2.id=r.somecolumn
LOOP
--perform calcs here
end loop;
END LOOP;
Upvotes: 2