Skip to content

How to perform query on two unrelated tables

I have a table A with Id and Geometry

enter image description here

And Temporary table B

enter image description here

Each Geometry of Temporary table B has intersecting geometry in Table A. I want to find the intersecting geometry and make a union of the geometry. The final table should be id of Table A which is having intersection and the union of geometry. If there are more than 1 intersecting geometry then pick any one.

enter image description here

I can not perform join here as there is no common column between these tables so don’t know how to get the final result.



In the demo, I took types intrange for simulating the types geometry. Ranges are close enough to get the same query:


SELECT DISTINCT ON (       -- 3,
    a.geom + b.geom             -- 2
JOIN b ON a.geom && b.geom      -- 1
  1. Join condition should be the check for intersection. For ranges it is && operator, in your case it should be st_intersects(a.geom, b.geom)
  2. Union both geometries. Here it is done using the + operator, in your case it should be st_union(a.geom, b.geom)
  3. DISTINCT ON( ensures that there’s only one record per

So, your final query should look like this:

SELECT DISTINCT ON (                    -- 3,
    st_union(a.geom, b.geom)                 -- 2
JOIN b ON st_intersects(a.geom, b.geom)      -- 1
2 People found this is helpful