Выделите столбцы и в столбце jsonb верните только последний элемент, который соответствует - PullRequest
0 голосов
/ 11 ноября 2018

У меня есть таблица documents, я хочу выбрать столбцы foo и bar. А также столбец comments, который jsonb.

Но в comments мне нужен только последний элемент, который удовлетворяет условию "isUser":false.

"select foo, bar, comments from documents 
 where comments @> '[{"isUser":false}]' 
 limit 1 " /*just limit by 1, the latest comment where isUser = false*/

Вот как выглядит json внутри столбца comments:

[{
    "text": "1 sample lorem ipsum",
    "authorId": "0dcd5a36-2778-4fc4-bbc1-112ed61f1362",
    "timestamp": "2018-11-11T08:46:39.608Z",
    "isUser": false
},{
    "text": "2 sample lorem",
    "authorId": "0dcd5a36-2778-4fc4-bbc1-112ed61f1362",
    "timestamp": "2018-11-11T08:46:41.237Z",
    "isUser": true
},{
...]

Для comments Мне нужен только последний объект, в котором "isUser":false

1 Ответ

0 голосов
/ 11 ноября 2018

Вы можете использовать jsonb_array_elements .. WITH ORDINALITY, чтобы получить заказ

select foo, bar, j.comments
from 
  documents cross 
  join lateral jsonb_array_elements(comments) WITH ORDINALITY j(comments, rn)
WHERE 
  (j.comments ->> 'isUser'):: boolean is false
  ORDER BY j.rn DESC LIMIT 1;

EDIT

Я хочу ограничить 1 json-объектом внутри jsonarray в комментариях

select DISTINCT ON ( foo, bar) foo,bar,comments
FROM 
( select d.foo,d.bar,j.comments,j.rn
from 
  documents d cross 
    join lateral jsonb_array_elements(comments) WITH ORDINALITY j(comments, rn)
WHERE 
  (j.comments ->> 'isUser'):: boolean is false
  ) s
  ORDER BY foo,bar,rn desc  ;

Демо

...