How to select inside a FOR-Loop for further computations?

落爺英雄遲暮 提交于 2019-12-13 02:35:01

问题


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.


回答1:


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';



回答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;


来源:https://stackoverflow.com/questions/27450490/how-to-select-inside-a-for-loop-for-further-computations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!