从联接表创建 JSON

Create JSON from joined tables

如何根据以下语句创建 JSON(B):

SELECT *
FROM foo
LEFT JOIN bar
  USING (id)

我的解决方案目前是这样的:

SELECT to_jsonb(foo) || coalesce(to_jsonb(bar), '{}')
FROM foo
LEFT JOIN bar
  USING (id)

每加入一个 table,这就会变得更丑陋,例如:

SELECT to_jsonb(foo) || coalesce(to_jsonb(bar), '{}') || coalesce(to_jsonb(baz), '{}')
FROM foo
LEFT JOIN bar
  USING (id)
LEFT JOIN baz
  USING (id)

我想要这样的东西:

SELECT to_jsonb(*)
FROM foo
LEFT JOIN bar
  USING (id)

但这给了我:

[42883] ERROR: function to_jsonb() does not exist

第三个查询生成 barbaz 中所有行的笛卡尔积与相同的 id。无论是否有意,您都可以使用派生的 table,将转换为 JSON 移动到外部查询。

select to_jsonb(q)
from (
    select *
    from foo
    left join bar using(id)
    left join baz using(id)
    ) q