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

标签 python sql arrays database postgresql

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

我试过的方法:

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

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

有什么优雅的方法可以做到这一点吗?

最佳答案

您可以通过使用 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;

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

希望对您有所帮助 :) 如有任何疑问,请随时提出。

关于python - PostgreSQL - 查询所有表的所有表列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51941149/

相关文章:

python - 在 __init__ 中更改类属性

python - 如何在Python2 CLI中制作交互式选择菜单?

mysql - Mysql中有两个表数据的多个条件

sql - 使用xQuery提取SQL变量中也存在的属性值

java - 线程ArrayIndex异常

python - TypeError : int() argument must be a string, 类字节对象或数字,不是 'datetime.datetime'

python - 是否可以通过事务方式改变 GAE 实体?

c - 多维数组的某些元素错误地读为零

sql - 如何在给定一组满足条件的值的情况下查找最近日期*

c# - 如何在不知道要存储多少值的情况下创建数组?