I have a setup where I would like to support a user defined subquery inside of a spatial query to identify overlapping polygons. Below is an example:
SELECT i1.id, i2.id
FROM
(SELECT * FROM Images WHERE id > 600) i1,
(SELECT * FROM Images WHERE id > 600) i2
WHERE ST_INTERSECTS(i1.footprint_latlon, i2.footprint_latlon) = TRUE
AND i1.id > i2.id
The above is working, but I more canonical way to do this exists.
The inner query is completely arbitrary here and the important component is that I am defining i1 and i2 using an identical query. I am doing this so that I have i1 and i2 aliases for the outer, spatial query.
Is it necessary to execute the inner query twice or does a better way to create the i1, and i2 aliases exist? Lots of example on executing subqueries with a single (mandatory alias), but I am not seeing any examples of 'multi-aliases'.
WITH i AS (foo) SELECT bah FROM i AS i1, i AS i2 WHERE...the sub query is effectively resolved twice. To avoid that YOU need to preserve the result, such as with a temp table. But doing so may not be a good idea; you need to write the results somewhere and lose the indexes, etc. For that reason caching the results may be more expensive than resolving it twice. Also, note that sql is a declarative language and the rdbms is free to rearrange the execution, so as to make use of indexes, etc. In short, don't prematurely optimise. Be concerned with maintainable code.