我正在尝试在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是否存在于other_field
表示的列表中,我应该如何编写查询?
使用运算符@>
。根据文档:
@>jsonb 左侧 JSON 值是否在顶层包含正确的 JSON 路径/值条目?
例:
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)