1

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

结构看起来像这样。

Events
_ _ _ _

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

id: UUID
name: varchar

我正在尝试使用下面的查询来加入表,但我无法将类型 JSONB 转换为 uuid[]不允许设置返回函数

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;

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

4

1 回答 1

1

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

…
LEFT JOIN activities ON activities.id IN (
  SELECT el::uuid
  FROM jsonb_array_elements_text(events.fields -> 'activities') AS el
)
于 2021-07-27T22:40:54.867 回答