ruby-on-rails - 内部加入 postgres 数组字段

标签 ruby-on-rails postgresql jsonb

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

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

enter image description here

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

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

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

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

从 page_pieces 中选择 page_id = 50806 的片段

遍历每个片段

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

所以我的问题是 我们可以编写单个 join 语句 来获取所有片段及其 included_on_pages

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

最佳答案

我认为结合使用取消嵌套、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

关于ruby-on-rails - 内部加入 postgres 数组字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46660795/

相关文章:

ruby-on-rails - 在 Google Cloud App Engine 中托管 Rails App 并设置环境变量

sql - 需要帮助 postgresql 交叉表查询

mysql - 如何将 SQL 查询转换为 Rails Active Record 查询?

arrays - "[XX000] ERROR: failed to build any 3-way joins"Postgresql 错误是什么意思?

postgresql - 为什么 Postgres 对 jsonb 列的查找如此缓慢?

jquery - 我的 .on() 的行为类似于 .bind(),而不是 .live()

javascript - 有没有任何API或Rails gem可以提取所有股票的主列表?

ruby-on-rails - Rails 4 simple_form has_many 通过复选框不保存

sql - 在另一个表中的一行的 UPDATE 中使用同一个表中的多行

postgresql - 从 Postgres 的 jsonb 中选择匹配元素