我们有一个使用rails、react和postgresql的CMS。我们的桌子里有书页和碎片。
每页由一组片段(数组字段)组成。
我们有可以跨多个页面使用的片段。
假设我们正在呈现页面id50806
。我们的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
最佳答案
我认为不必要的比较和数组聚合的组合应该可以工作:
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