【问题标题】:How to UNION a list of tables retrieved from another table with a single query?如何使用单个查询联合从另一个表中检索到的表列表?
【发布时间】:2019-07-01 05:13:03
【问题描述】:

我有一个表,其中包含 PostgreSQL 中的表列表:

|id|table |
|--|------|
|1 |table1|
|2 |table2|
|3 |table3|

我想从所有这些表的联合中进行选择,例如(伪代码):

select * from union(select table from tablenames)

【问题讨论】:

  • 您可能需要编写一个存储过程来执行此操作。
  • 这听起来像是一个有问题的桌子设计。您试图解决的根本问题是什么? Partitioning 可能就是你要找的。​​span>

标签: sql postgresql union dynamic-sql


【解决方案1】:

要自动执行此操作,您需要动态 SQL

CREATE OR REPLACE FUNCTION f_multi_select()
  RETURNS SETOF table1
  LANGUAGE plpgsql AS
$func$
BEGIN
   RETURN QUERY EXECUTE
   (
   SELECT string_agg(format('SELECT * FROM %I', tbl), ' UNION ALL ')
   FROM   (SELECT tbl FROM tablenames ORDER BY id) sub
   );
END
$func$;

呼叫:

SELECT * FROM f_multi_select();

假设所有表共享相同的行类型 - 所以我们可以选择任何一个来定义函数的返回类型。

我用ORDER BY 加入了一个子查询——以防表的顺序有意义。

相关:

【讨论】:

    【解决方案2】:

    这是一种无需使用动态 SQL 即可执行此操作的方法。假设您的架构中只有 10 个可能的表。然后,您可以编写以下查询:

    select * from table1 where 'table1' in (select "table" from tablenames) union all
    select * from table2 where 'table2' in (select "table" from tablenames) union all
    select * from table3 where 'table3' in (select "table" from tablenames) union all
    ...
    select * from table10 where 'table10' in (select "table" from tablenames);
    

    这种方法的缺点是它需要对每个可能的表进行硬编码。

    我在这里还假设select * 有意义,因为十个表中的每一个都将具有相同数量和类型的列。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-06
      • 2019-06-02
      • 1970-01-01
      • 2018-05-13
      • 1970-01-01
      • 2011-08-26
      相关资源
      最近更新 更多