PostgreSQL - 查询所有表的所有表列

Eri*_*Kim 4 python sql database arrays postgresql

如何查询数据库中所有表的所有表列?

我试过的方法:

  1. 使用获取所有表名 select tablename from pg_tables where schemaname = 'public'
  2. 使用UNIONPostgres 的方法处理 cmd 字符串。
  3. 执行 cmd 字符串。

我在一个数据库中有 19 个表,我的方法导致查询时间慢了 19 倍。而且,它不会返回我想要的东西。所有表都有两列,其中一列始终是名为time. 使用该UNION方法不会返回 19 个time字符串。它只返回一个time字符串和 19 个其他列名。但是,我想是这样的: [('table_1', ['time', 'col']), ('table_2', ['time', 'col']), ('table_3', ['time', 'col])...]

有没有优雅的方法来做到这一点?

Nim*_*mal 7

您可以通过array_agg()information_schema.tablesinformation_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;
Run Code Online (Sandbox Code Playgroud)

在这里,我首先获取所有表,然后将其与列表连接,最后使用array_agg()将它们全部聚合到一个数组中,按表名分组。

希望它有帮助:) 如果您有任何疑问,请随时询问。