如何检查一个值是否存在于 JSONB 列表中
How to check if a value exists in a JSONB list
我试图在 PostgreSQL 11 JSONB 查询中找出答案
SELECT id, my_json_field #>> '{field_depth_1, field_depth_2}'
FROM my_data
WHERE my_json_field @> '{"other_field": 3}'::jsonb
如果 other_field
是一个键值对,这就完美了,我得到了 other_field = 3
的每一行。但是,如果 other_field
是一个值列表,例如:[2,3,6,8,10],我想为每一行找出值 3 是否存在于由 [=11 表示的列表中=], 查询应该怎么写?
使用运算符@>
。每 the documentation:
@> jsonb Does the left JSON value contain the right JSON path/value entries at the top level?
示例:
with my_data(id, my_json_field) as (
values
(1, '{"field_depth_1": {"field_depth_2": "something 1"}, "other_field": 3}'::jsonb),
(2, '{"field_depth_1": {"field_depth_2": "something 2"}, "other_field": 4}'),
(3, '{"field_depth_1": {"field_depth_2": "something 3"}, "other_field": [2,3,6,8,10]}'),
(4, '{"field_depth_1": {"field_depth_2": "something 4"}, "other_field": [2,4,6,8,10]}')
)
select id, my_json_field #>> '{field_depth_1, field_depth_2}' as value
from my_data
where my_json_field->'other_field' @> '3'
id | value
----+-------------
1 | something 1
3 | something 3
(2 rows)
我试图在 PostgreSQL 11 JSONB 查询中找出答案
SELECT id, my_json_field #>> '{field_depth_1, field_depth_2}'
FROM my_data
WHERE my_json_field @> '{"other_field": 3}'::jsonb
如果 other_field
是一个键值对,这就完美了,我得到了 other_field = 3
的每一行。但是,如果 other_field
是一个值列表,例如:[2,3,6,8,10],我想为每一行找出值 3 是否存在于由 [=11 表示的列表中=], 查询应该怎么写?
使用运算符@>
。每 the documentation:
@> jsonb Does the left JSON value contain the right JSON path/value entries at the top level?
示例:
with my_data(id, my_json_field) as (
values
(1, '{"field_depth_1": {"field_depth_2": "something 1"}, "other_field": 3}'::jsonb),
(2, '{"field_depth_1": {"field_depth_2": "something 2"}, "other_field": 4}'),
(3, '{"field_depth_1": {"field_depth_2": "something 3"}, "other_field": [2,3,6,8,10]}'),
(4, '{"field_depth_1": {"field_depth_2": "something 4"}, "other_field": [2,4,6,8,10]}')
)
select id, my_json_field #>> '{field_depth_1, field_depth_2}' as value
from my_data
where my_json_field->'other_field' @> '3'
id | value
----+-------------
1 | something 1
3 | something 3
(2 rows)