postgresql - Union-all postgresql select 子句保留顺序

标签 postgresql large-data olap

对 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
(
  ...
)

每个 都是相对轻量级的查询,它会生成大约 100K-1M 行,并且可以在内存中排序,而不会对性能产生重大影响。

结果查询由数万个多层嵌套的 UNION ALL 查询组成,按照严格的常规顺序,就像深度遍历树一样,因此结果查询是数十亿行的数据集。

所以问题是:由于SQL不保证UNION ALL语句的顺序,因此外部查询应该包含ORDER BY子句,但服务器硬件无法在要求的时间内执行数十亿行的排序。

但是,联合查询的顺序是严格确定的,应该是:等,按层次排序,所以实际上外层查询的排序是多余的,因为数据集已经按 SQL 查询结构排序。

有必要强制 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_idthe_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/

相关文章:

analytics - OLAP 和操作数据的联接查询

php - 使用 MDB2 防止 PHP 中的 SQL 注入(inject)

php - PostgreSQL: 未定义函数 array_agg(enumlabel)

arrays - 如何在 PostgreSQL 12 中将元素添加到 jsonb 数组中?

django - 调整 postgresql(使用 django 快速读取)

python - 使用 vaex 绘制大数据图

大数据集的Python defaultdict

python - 使用python加速将大型数据集从txt文件插入到mySQL

c# - 带有链接 OLAP 服务器的 SqlCommand.ExecuteScalar 不返回任何值

javascript - 浏览 OLAP 多维数据集