对 RDBMS Postgresql 进行复杂的 SQL 查询,其中包含多个嵌套的 UNION ALL 式嵌套查询,如下所示:
(
(
(<QUERY 1-1-1> UNION ALL <QUERY 1-1-2>) UNION ALL
(<QUERY 1-1-3> UNION ALL <QUERY 1-1-4>) UNION ALL
...
) UNION ALL
(
(<QUERY 1-2-1> UNION ALL <QUERY 1-2-2>) UNION ALL
(<QUERY 1-2-3> UNION ALL <QUERY 1-2-4>) UNION ALL
...
) UNION ALL
...
) UNION ALL
(
(
(<QUERY 2-1-1> UNION ALL <QUERY 2-1-2>) UNION ALL
(<QUERY 2-1-3> UNION ALL <QUERY 2-1-4>) UNION ALL
...
) UNION ALL
(
(<QUERY 2-2-1> UNION ALL <QUERY 2-2-2>) UNION ALL
(<QUERY 2-2-3> UNION ALL <QUERY 2-2-4>) UNION ALL
...
) UNION ALL
...
) UNION ALL
(
...
)
每个
结果查询由数万个多层嵌套的 UNION ALL 查询组成,按照严格的常规顺序,就像深度遍历树一样,因此结果查询是数十亿行的数据集。
所以问题是:由于SQL不保证UNION ALL语句的顺序,因此外部查询应该包含ORDER BY子句,但服务器硬件无法在要求的时间内执行数十亿行的排序。
但是,联合查询的顺序是严格确定的,应该是:
有必要强制 Postgres 保留嵌套 UNION ALL 语句的顺序。怎么做?欢迎任何插件、扩展甚至肮脏的黑客。
请避免在答案和评论中提及类似 XY 的问题 - 问题是以研究方式按原样制定的。数据库和数据集的结构不能因问题条件而改变。谢谢。
最佳答案
试试这个 - 将查询结果分配到临时表中。 这是一步一步:
- 创建一个临时表,例如。
the_temp_table
比如<QUERY 1-1-1>
的记录类型
create temporary table the_temp_table as <QUERY 1-1-1> limit 0;
- 添加自增主键列
extra_id
至the_temp_table
alter table the_temp_table add column extra_id serial primary key not null;
- 然后按照正确的顺序一一运行所有查询
insert into the_temp_table <QUERY 1-1-1>; insert into the_temp_table <QUERY 1-1-2>;
insert into the_temp_table <QUERY 1-1-3>; insert into the_temp_table <QUERY 1-1-4>;
insert into the_temp_table <QUERY 1-2-1>; insert into the_temp_table <QUERY 1-2-2>;
insert into the_temp_table <QUERY 1-2-3>; insert into the_temp_table <QUERY 1-2-4>;
-- continue
- 终于
select <fields list w/o extra_id> from the_temp_table order by extra_id;
-- no sorting is taking place here
因此,您将有效地模仿 UNION ALL
以受控方式进行,性能损失微乎其微。
关于postgresql - Union-all postgresql select 子句保留顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72002270/