【问题标题】:Inner join with postgres array field与 postgres 数组字段的内部连接
【发布时间】:2017-10-10 07:22:44
【问题描述】:

我们有一个使用 rails、react 和 postgresql 的 CMS。我们的表中存储了页面和片段。 每个页面由一组片段(一个数组字段)组成。

我们有可以跨多个页面使用的片段。

假设我们正在渲染 page_id 50806。我们的 React 前端需要以下格式的数据。

pieces: [
 {id: B1fu5jthb, included_on_pages: [50808, 50806]},
 {id: BJTNssF2Z, included_on_pages: [50808]}
]

所以目前,为了找到included_on_pages,我正在编写一个查询来获取页面的所有片段,然后循环遍历每个片段以查找包含特定片段的页面。

(基本上是 N+1 个查询。)

select pieces from page_pieces where page_id = 50806

Looping over each piece

select page_id from page_pieces where 'B1fu5jthb' = any(page_pieces.pieces);

所以我的问题, 我们可以编写一个join statements 来获取所有片段及其included_on_pages

,而不是遍历每个片段并查找其中包含的页面

【问题讨论】:

    标签: ruby-on-rails postgresql jsonb


    【解决方案1】:

    我认为取消嵌套、ANY 比较和数组聚合的组合应该可以工作:

    with
      pcs as (select unnest(pieces) as id from page_pieces where page_id = 50806)
    select id, array_agg(page_id) as included_on_pages
    from pcs inner join page_pieces on id = any(pieces)
    group by id;
    

    See it on SQL Fiddle

    【讨论】:

      猜你喜欢
      • 2017-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-19
      • 1970-01-01
      • 2017-01-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多