如何将 PostgreSQL JSONB 数据与外部连接 Table

How to Join PostgreSQL JSONB Data with Foreign Table

我有一个 PostgreSQL 数据库 table,其中的 JSONB 列包含外部 table 的键。

结构看起来像这样。

Events
_ _ _ _

id:uuid
name: uuid
fields: JSONB { 
      date {},
      activities: ['uuid','uuid']
           }
...others columns
Activities
_ _ _ _ _ _ 

id: UUID
name: varchar

我正在尝试使用下面的查询来加入 tables 但我得到 cannot cast type JSONB to uuid[] or set -不允许返回函数

SELECT
  to_json(src) :: json AS event
FROM
  (
    SELECT
      events.id AS id,
      events.name AS name,
      events.fields -> 'time' AS time,
      events.fields ->> 'poster' AS poster,
      events.fields ->> 'address' AS address,
      categories.name AS category,
      -- array_agg(DISTINCT activities.name) AS activities,
      events.age_limit AS age_limit,
      min(tickets.price) AS least_ticket,
      events.description AS description,
      to_json(profiles.*) AS organizer,
      timezones.short_code AS timezone,
      array_agg(DISTINCT tickets.*) AS tickets,
      to_json(currencies.*) AS currency
    FROM
      events
      LEFT JOIN categories ON categories.id = (events.fields ->> 'category_id') :: uuid
      LEFT JOIN activities ON activities.id = Any(
        jsonb_build_array(events.fields ->> 'activities') :: uuid [ ]
      ) 
      LEFT JOIN tickets ON tickets.event_id = events.id
      LEFT JOIN profiles ON events.user_id = profiles.user_id
      LEFT JOIN currencies ON currencies.id = events.currency_id
      LEFT JOIN timezones ON events.timezone_id = timezones.id
    WHERE
      events.slug = 'annes-wedding-nqbh'
    GROUP BY
      events.name,
      categories.id,
      events.id,
      profiles.id,
      currencies.id,
      timezones.id
  ) src;

请问我加入这些 table 的最佳方式是什么,以及在活动字段具有包含键和值的数组的情况下。

您不能将 jsonb 转换为 uuid,但您应该能够将 jsonb 数组元素转换为 text,然后转换为 uuid(假设这是您将 UUID 存储在 JSON 中)。但请注意,您需要单独执行此操作,而不是一次对整个数组执行此操作:

…
LEFT JOIN activities ON activities.id IN (
  SELECT el::uuid
  FROM jsonb_array_elements_text(events.fields -> 'activities') AS el
)