[英]SQL multiple alias in subquery
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. 内部查询在这里是完全任意的,重要的组成部分是我使用相同的查询来定义
i1
和i2
。 I am doing this so that I have i1
and i2
aliases for the outer, spatial query. 我这样做是为了对外部空间查询使用
i1
和i2
别名。
Is it necessary to execute the inner query twice or does a better way to create the i1
, and i2
aliases exist? 是否需要两次执行内部查询,还是有更好的方法来创建
i1
和i2
别名? Lots of example on executing subqueries with a single (mandatory alias), but I am not seeing any examples of 'multi-aliases'. 关于使用单个(强制别名)执行子查询的很多示例,但是我看不到“多重别名”的任何示例。
I don't think there is a clean easy way to "alias an alias". 我认为没有简单的“别名别名”方法。 You could do something like this:
您可以执行以下操作:
WITH
i1 AS (SELECT * FROM Images WHERE id > 600),
i2 AS (SELECT * FROM i1)
SELECT i1.id, i2.id
FROM
i1, i2
WHERE ST_INTERSECTS(i1.footprint_latlon, i2.footprint_latlon) = TRUE
AND i1.id > i2.id
EDIT and much nicer, as suggested by @MatBailie : 编辑和好得多,如@MatBailie所建议:
WITH
i AS (SELECT * FROM Images WHERE id > 600)
SELECT i1.id, i2.id
FROM
i AS i1, i AS i2
WHERE ST_INTERSECTS(i1.footprint_latlon, i2.footprint_latlon) = TRUE
AND i1.id > i2.id
My inclination would be one of the following: 我的倾向是以下之一:
select i1.id, i2.id
from images i1 join
images i2
on st_intersects(i1.footprint_latlon, i2.footprint_latlon)
where i1.id > 600 and i2.id > i1.id;
Or: 要么:
with ix as (
select i.*
from images i
where i.id > 600
)
select i1.id, i2.id
from ix AS i1 join
ix AS i2
on st_intersects(i1.footprint_latlon, i2.footprint_latlon)
where i2.id > i1.id;
I don't think there is a shortcut on performing the self join. 我认为执行自连接没有捷径可走。
If you don't want to repeat the (complicated) subquery, you could either use a CTE (see Gordon Linoff's answer) or use a (temp) view containing the subquery [a CTE behaves differently for the optimiser/planner, for larger resultsets this could cause subobtimal performance] : 如果您不想重复(复杂的)子查询,则可以使用CTE(请参阅Gordon Linoff的答案),也可以使用包含子查询的(临时)视图[对于较大的结果集,CTE在优化器/计划器中的行为有所不同。这可能会导致下意识的表现]:
CREATE TEMP VIEW vv AS
-- Put your complex subquery here ...
SELECT * FROM Images WHERE id > 600
;
SELECT i1.id, i2.id
FROM vv i1
JOIN vv i2 ON ST_INTERSECTS(i1.footprint_latlon, i2.footprint_latlon)
AND i1.id > i2.id
;
SELECT i1.id, i2.id
FROM Images i1,Images i2,
WHERE i2.id > 600
AND i1.id > i2.id
AND ST_INTERSECTS(i1.footprint_latlon, i2.footprint_latlon) = TRUE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.