#sql #arrays #json #postgresql #lateral-join
#sql #массивы #json #postgresql #боковое соединение
Вопрос:
Я хочу извлечь значение ключа из (обнуляемого) поля JSONB. Если поле равно нулю, я хочу, чтобы запись все еще присутствовала в моем результирующем наборе, но с нулевым полем.
customer
таблица:
id, name, phone_num, address
1, "john", 983, [ {"street":"23, johnson ave", "city":"Los Angeles", "state":"California", "current":true}, {"street":"12, marigold drive", "city":"Davis", "state":"California", "current":false}]
2, "jane", 9389, null
3, "sally", 352, [ "street":"90, park ave", "city":"Los Angeles", "state":"California", "current":true} ]
Текущий запрос PostgreSQL:
select id, name, phone_num, items.city
from customer,
jsonb_to_recordset(customer) as items(city str, current bool)
where items.current=true
Он возвращает:
id, name, phone_num, city
1, "john", 983, "Los Angeles"
3, "sally", 352, "Los Angeles"
Требуемый вывод:
id, name, phone_num, city
1, "john", 983, "Los Angeles"
2, "jane", 9389, null
3, "sally", 352, "Los Angeles"
Как мне добиться вышеуказанного результата?
Ответ №1:
Используйте a left join lateral
вместо неявного бокового соединения:
select c.id, c.name, c.phone_num, i.city
from customer c
left join lateral jsonb_to_recordset(c.address) as i(city str, current bool)
on i.current=true