将一对多关系转换为PostgreSQL中的json列

问题描述 投票:0回答:1

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

表格名称-列_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 json postgresql group-by information-schema
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.