0

I have a postGIS table:

id    value    geometry
0     10       'g_0_10'
0     20       'g_0_20'
1     10       'g_1_10'
1     20       'g_1_20'
2     10       'g_2_10'
2     20       'g_2_20'
...

Now I have a web application where I want the user to see the intersection of the above geometries for any list of id, grouped by value.

For example, the user wants to see the intersection of geometries for the id list = [x,y,z].

So I want a result that looks like this:

value    geoemtry
10       st_intersection(g_x_10, g_y_10, g_z_10)
20       st_intersection(g_x_20, g_y_20, g_z_20)

Can you write such a query if you don't know in advance the size of the list?

More generaly when trying to build dynamic sql queries from Python, do you have to concatenate strings like :

request = "select * from t where id=" + id + ";"

Or is there a cleaner way ?

2
  • Can you build an 'in' statement to pass along instead? An 'in' statement can have 1 value or many values, so it would work if only 1 ID is chosen... Commented Sep 22, 2015 at 15:34
  • While your question may just be conceptual code, you should read up on SQL Injection, too, and adjust your final code design. Imagine if I gave a list like: "1; DROP DATABASE [master]" Commented Sep 24, 2015 at 20:10

1 Answer 1

1

Your Main problem here is that ST_Intersection() can only take 2 arguments. Maybe there is an array version of it but I Don't know about, maybe if someone already wrote it you can save yourself a lot of time. Have you searched for it?

If not no matter what implementation you choose you'll need a loop of some sort in order to:

  1. Make a list of all the geometry you want to get the intersection
  2. ST_Intersection 1rst geometry with the 2nd geometry
  3. Store the running result
  4. ST_Intersection the running result with the next geometry
  5. Repeat 3&4 until there is no more n next geometry

So IMHO there are 2 roads to investigate.

  1. You can write a PL/pgSQL function which allow dynamics query and all the loop you want. You then can use all existing object type of PostgeSQL/PostGis so that can really be easier than developing an external application. On top of that end user will stick to plain SQL and use you PL/pgSQL function as an "in-database API".

  2. You might try to use a combination of PostgresSQL Window functions and Recursive CTE Query to reach you goal. Less programming, but more complexity of the resulting SQL. In theory with a clever trick you might totally avoid the need of dynamic query using that method.

Both way require spending some time over the PostgreSQL manual even if you are a power user. And I have no clue of which option would be the most performance friendly (though I might bet on PL/pgSQL).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.