问题
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