1

Используется PostgreSQL старше 12 версии

Имеется таблица table, в ней есть столбцы item_id и attributes типа jsonb. Выглядит она так:введите сюда описание изображения

Необходимо добавить новый столбец attributes_ids и удалить attributes. Новый столбец должен содержать массив чисел, полученных путем замены json'а на значение его поля id.

2 ответа 2

2

jsonb_array_elements и array_agg:

select 
  item_id, 
  (select array_agg((j->>'id')::int) from jsonb_array_elements(attributes) j) ids
from _table;
1

Можно использовать lateral join и jsonb_to_recordset:

select item_id, array_agg(id) as attribures_id
from (
   select *, row_number() over() as rn
   from t
) as t,
lateral jsonb_to_recordset(t.attributes) as (id integer, value integer)
group by rn, item_id;

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.