PostgreSQL-基于列数的表UNION

问题描述

我正在Postgresql中工作,我想将一个名为“ postgres”的数据库的所有11列表统一。

上述表的列表,我通过以下查询得到它。

with  
completo_tablas as (
select column_name,table_name from information_schema.columns
where table_schema='public'
)
--,tablas as (
select table_name--,count(column_name)
from completo_tablas
group by table_name
having count(column_name)=11
--)

服药,类似:

Table_name
--------------  
table1  
table2  
.  
.  
.  

我无法解决的问题是,在特定的一天中无法获得具有11列的表的UNION;我知道我可以复制表名称,例如:

Select * from tabla1 UNION select * from tabla2 UNION Sel....

鉴于我们的业务性质,随着时间的流逝,桌子的数量将会增加

由于我们业务的本质,我想要的是一个“动态”查询,在该查询中我没有在UNION查询中手动设置表的名称

但是总能得到的东西,就是所有具有11列的表的联合

谢谢您的时间。

解决方法

您可以尝试参照下面的表格来简化任务,但是您应该同意这确实是一个很奇怪的要求,因为您不能保留数据,因为数据库对象同样没有其他标准方法。

 \o path/file.sql

  with  
completo_tablas as (
select column_name,table_name from information_schema.columns
where table_schema='public'
),tablas as (
select table_name--,count(column_name)
from completo_tablas
group by table_name
having count(column_name)=11
)
 select 'select * from '|| table_name||' union'
 from tablas

 \o

  \i file.sql