Python PostgreSQL-查询所有表的所有表列
如何查询数据库中所有表的所有表列 我尝试过的方法: 从schemaname='public'的pg_表中使用selecttablename获取所有表名 使用Postgres的UNION方法处理cmd字符串。 执行cmd字符串。 我在一个数据库中有19个表,我的方法导致查询时间慢19倍。而且,它也不会返回我想要的东西。所有表都有两列,其中一列始终是名为time的列名。使用UNION方法不会返回19个时间字符串。它只返回一个时间字符串和19个其他列名。但我想要这样的东西: [table_1'、[time'、[col']、[table_2'、[time'、[col']、[table_3'、[time'、[col]…]Python PostgreSQL-查询所有表的所有表列,python,sql,arrays,database,postgresql,Python,Sql,Arrays,Database,Postgresql,如何查询数据库中所有表的所有表列 我尝试过的方法: 从schemaname='public'的pg_表中使用selecttablename获取所有表名 使用Postgres的UNION方法处理cmd字符串。 执行cmd字符串。 我在一个数据库中有19个表,我的方法导致查询时间慢19倍。而且,它也不会返回我想要的东西。所有表都有两列,其中一列始终是名为time的列名。使用UNION方法不会返回19个时间字符串。它只返回一个时间字符串和19个其他列名。但我想要这样的东西: [table_1'、[ti
有什么优雅的方法可以做到这一点吗?因为您使用的是Python,如果您分两步来处理这个问题,我想这是最清楚的。首先,使用此查询检索表/列名对:
select table_name, column_name
from information_schema.columns
where table_name in (
select tablename from pg_tables where schemaname = 'public');
然后,将结果粘贴到defaultdict中:
from collections import defaultdict
my_cols = <your code to execute the query above and fetch all rows>
column_mapping = defaultdict(list)
for tablename, colname in my_cols:
column_mapping[tablename].append(colname)
您可以在单个查询中使用数组_agg和information_schema.tables和information_schema.columns表上的联接来完成此操作 这将返回与预期输出类似的结果:
select
t.table_name,
array_agg(c.column_name::text) as columns
from
information_schema.tables t
inner join information_schema.columns c on
t.table_name = c.table_name
where
t.table_schema = 'public'
and t.table_type= 'BASE TABLE'
and c.table_schema = 'public'
group by t.table_name;
在这里,我首先获取所有表,然后将其与列表联接,最后使用array_agg将它们聚合到一个数组中,按表名分组
希望有帮助:如果你有任何疑问,尽管问
>>> column_mapping.items()
[('table_1', ['time', 'col']), ('table_2', ['time', 'col']), ('table_3', ['time', 'col])]
select
t.table_name,
array_agg(c.column_name::text) as columns
from
information_schema.tables t
inner join information_schema.columns c on
t.table_name = c.table_name
where
t.table_schema = 'public'
and t.table_type= 'BASE TABLE'
and c.table_schema = 'public'
group by t.table_name;