1

Working with postgresql and postgis I have 2 openstreetmap tables, containing:

  1. Point: Locations with a single coordinate
  2. Polygon: Areas with sets of coordinates

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.

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
Patrick
  • 458
  • 6
  • 12

2 Answers2

2

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;
Joe Love
  • 5,594
  • 2
  • 20
  • 32
  • 1
    Thanks Joe, much Love to you! – Patrick Dec 12 '14 at 21:37
  • I answered your question directly, however, Erwin's answer is a better solution to the overall problem you're trying to solve. My solution just solved your syntax issues, not your method of querying. – Joe Love Dec 15 '14 at 21:05
2

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';
Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228