如果两个 PostgreSQL table 有 gist 索引,他们的联合是否可以被认为是一个索引 table?

If two PostgreSQL table has gist index, can their union be considered as an indexed table?

我有三个table,table_atable_btable_c。他们都有要点索引。 我想在 table_ctable_atable_b 的 UNION 之间执行左连接。 可以将 UNION 视为“索引”吗?我认为最好创建新的 table 作为 UNION,但是这些 table 很大,所以我尽量避免这种冗余。

关于SQL,我的问题:

这是

SELECT * FROM myschema.table_c AS a
LEFT JOIN
(SELECT col_1,col_2,the_geom FROM myschema.table_a
UNION
SELECT col_1,col_2,the_geom FROM myschema.table_b) AS b
ON ST_Intersects(a.the_geom,b.the_geom);

等于这个?

CREATE TABLE myschema.table_d AS
SELECT col_1,col_2,the_geom FROM myschema.table_a
UNION
SELECT col_1,col_2,the_geom FROM myschema.table_b;

CREATE INDEX idx_table_d_the_geom
ON myschema.table_d USING gist
(the_geom)
TABLESPACE mydb;

SELECT * FROM myschema.table_c AS a
LEFT JOIN myschema.table_d AS b
ON ST_Intersects(a.the_geom,b.the_geom);

你可以用EXPLAIN查看执行计划,但我怀疑它会使用索引。

与其在一个 table 和另外三个 table 的并集之间执行左连接,不如在一个 table 和每个 table 之间执行左连接的并集依次为三个 table。这将是一个更长的语句,但如果可以加速左连接,PostgreSQL 一定会使用索引。

一定要使用 UNION ALL 而不是 UNION 除非你真的必须删除重复项。