使用postgres数组字段

时间:2017-10-10 07:22:44

标签: ruby-on-rails postgresql jsonb

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

我们有多个页面可以使用。

enter image description here

我们说我们正在渲染page_id 50806。我们的反应前端需要采用以下格式的数据。

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

,而不是遍历每个部分并查找其中包含的部分。

1 个答案:

答案 0 :(得分:0)

我认为,取消,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

相关问题