如何使用单个查询统一从另一个表检索的表的列表?

时间:2019-07-01 05:13:03

标签: sql postgresql union dynamic-sql

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

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

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

select * from union(select table from tablenames)

2 个答案:

答案 0 :(得分:2)

要使其自动化,您需要动态SQL

isHidden

致电:

CREATE OR REPLACE FUNCTION f_multi_select()
  RETURNS SETOF table1 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$  LANGUAGE plpgsql;

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

我使用SELECT * FROM f_multi_select(); 进行了子查询-以防表的顺序有意义。

相关:

答案 1 :(得分:0)

这是无需使用动态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 *是有意义的,因为十个表中的每个表将具有相同数量和类型的列。