Select columns and in a jsonb column only return the last element where meets condition

旧城冷巷雨未停 提交于 2019-12-11 19:06:40

问题


I have table documents, I want to select columns foo and bar. And also the column comments which is jsonb.

But in comments I only need the last element that meets condition "isUser":false.

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

This is how the json looks liks inside comments column:

[{
    "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
},{
...]

For comments I only need the last object in which "isUser":false


回答1:


You may use jsonb_array_elements .. WITH ORDINALITY to get the order

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

I want it to limit to 1 json object inside the jsonarray in comments

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  ;

Demo



来源:https://stackoverflow.com/questions/53247482/select-columns-and-in-a-jsonb-column-only-return-the-last-element-where-meets-co

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!