简化 PostgreSQL 中复杂的 union all
我在 PostgreSQL 中有一个非常复杂的查询,它联合了多个表,所有这些表都有我们想要联合的公共字段集。目前我们正在预生成此查询。我已经看到使用 UNPIVOT 的解决方案,我想知道是否可以在 PostgreSQL 风格的 SQL 中执行此操作。
我所拥有的就是
SELECT a,b,c FROM a UNION ALL
SELECT a,b,c FROM c UNION ALL
SELECT a,b,c FROM d UNION ALL
SELECT a,b,c FROM e UNION ALL
SELECT a,b,c FROM f
我想要将表的名称合并到单独的表中并将其用于此查询。
附言。更改架构不是一个选项。
I have very complex query in PostgreSQL that unions several tables, that all have common set of fields we want to union. currently we're pregenerating this query. I have seen solution to this using UNPIVOT and I'm wondering if it's possible to do this in PostgreSQL flavour of SQL.
What I have is something like
SELECT a,b,c FROM a UNION ALL
SELECT a,b,c FROM c UNION ALL
SELECT a,b,c FROM d UNION ALL
SELECT a,b,c FROM e UNION ALL
SELECT a,b,c FROM f
I'd like to have names of tables to union in separate table and use that for this query.
PS. Changing schema is not an option.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 Postgres 文档的继承来实现继承。您需要重新创建数据库,但是如果您转储没有架构的表,创建具有继承的新架构,然后加载回数据,那么这很容易。
该架构看起来像这样:
通过此设计,您可以进行简单的选择:
这将返回
base
中的所有行以及从base
继承的所有表。如果您还没有阅读过有关 PostgreSQL 表分区的文档,请参阅已经这样做了。
Use inheritance for the Postgres documentation for inheritance. You'll need to recreate the database, but that's easy if you dump the tables without schema, create a new schema with inheritance, and load the data back.
The schema would look something like this:
With this design, you can do a simple select:
This will return all rows in
base
and all the tables inheriting frombase
.Read about PostgreSQL table partitioning from the docs if you haven't done so already.
如果你真的无法修复你的设计(或者不想使用 jmz 的非常好的建议),你唯一的选择可能是一个集合返回函数,它“即时”构建必要的 UNION,然后返回结果那。
该函数根据 union_source 中的表名构建必要的 UNION,然后执行 union 并返回结果。
如果列并不总是具有相同的名称,您可以扩展 union_source 表来存储每个表的列列表。
要使用此功能,只需从中选择:
If you really can't fix your design (or don't want to use the very good suggestion from jmz), your only choice is probably a set returning function that builds the necessary UNION "on the fly" and then returns the results from that.
The function builds the necessary UNION based on the table names in union_source and then executes the union and returns the result.
You could extend the union_source table to also store the column list for each table, if the columns do not always have the same names.
To use this function, simply select from it: