【问题标题】:MongoDB-esq SQL queryMongoDB-esq SQL 查询
【发布时间】:2020-08-24 21:46:38
【问题描述】:

假设我有一个与其他 2 个表有 2、1:n 关系的主表。 e.i 一个组将有许多频道和许多用户。

在 MongoDB 中,我可以通过 single 查询获得组的全面 JSON 表示。即

{
  group_id: n,
  display_name: n,
  followers: n,
  channels: [
    {
      id: n,
      name: m
    },
    {
      id: n,
      name: m
    }...
  ],
  users: [
    {
      id: n,
      name: m
    },
    {
      id: n,
      name: m
    }...
  ]
}

有没有一种很好的方法可以在 pg 中获得与此类似的结果,而不必分别查询属于某个组的相关 channelsusers

【问题讨论】:

    标签: sql mongodb postgresql


    【解决方案1】:

    我最终使用了 postgres 中提供的 JSON 命令。以下查询有助于实现上述结果:

    select row_to_json(t)
    from (
      select id, followers, image_url,
      (
        select json_agg(row_to_json(s))
        from (
            select channel_id, channel_name
            from public.post_channel
            where group_id=groups.id
        ) s
      ) as channels
      from public.groups
    ) t 
    where id = '2677abe1-2164-4646-875b-af65a5ba1786';
    

    给出了结果:

    {
      "id": "2677abe1-2164-4646-875b-af65a5ba1786",
      "followers": 1,
      "image_url": "https://host.com/HomePageMockUp.PNG",
      "channels": [
        {
          "channel_id": "b0767288-f522-490a-a90f-93df0694355b",
          "channel_name": "Announcements"
        },
        {
          "channel_id": "075bba44-42c0-42b2-845f-4912cc34e762",
          "channel_name": "General"
        }
      ]
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-11
      • 2011-12-09
      相关资源
      最近更新 更多