【问题标题】:Converting one to many relation into a json column in PostgreSQL将一对多关系转换为 PostgreSQL 中的 json 列
【发布时间】:2020-07-16 18:48:38
【问题描述】:

我正在尝试查询 PostgreSQL 中的两个 information_schema 表 - 表和列,以获得以下结果:

table_name - columns_as_json_array

将这种一对多关系转换为 json 数组列。 我尝试了很多不同的方法,并想出了这样的东西:

SELECT t.table_name, c.json_columns
FROM information_schema.TABLES t
LEFT JOIN LATERAL(
  SELECT table_name, json_agg(row_to_json(tbc)) AS json_columns
  FROM information_schema.COLUMNS tbc
  WHERE t.table_name = tbc.table_name
  GROUP  BY table_name
  ) as c ON TRUE;

这会产生一个 table_names 列表,但 json_columns 始终包含所有可用的列,而不是该特定表的列。

有什么想法吗?

【问题讨论】:

    标签: sql arrays json postgresql group-by


    【解决方案1】:

    我真的不明白横向连接的意义。至于关注点,你可以通过聚合information_schema.columns得到预期的结果:

    select table_name, json_agg(row_to_json(c)) json_columns
    from information_schema.columns c
    group by table_name
    order by table_name
    

    【讨论】:

      猜你喜欢
      • 2012-08-22
      • 1970-01-01
      • 2021-02-10
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多