Select 列并且仅在 jsonb 列中 return 满足条件的最后一个元素
Select columns and in a jsonb column only return the last element where meets condition
我有 table documents
,我想要 select 列 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
中的最后一个对象
您可以使用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;
编辑
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 ;
我有 table documents
,我想要 select 列 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
您可以使用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;
编辑
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 ;