【问题标题】:How to check if a value exists in a JSONB list如何检查一个值是否存在于 JSON 列表中
【发布时间】:2019-10-07 18:45:32
【问题描述】:

我正在尝试在 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 表示的列表中,如何我应该写查询吗?

【问题讨论】:

    标签: json postgresql jsonb postgresql-11


    【解决方案1】:

    使用运算符@>。每the documentation:

    @> 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)    
    

    【讨论】:

      猜你喜欢
      • 2019-06-22
      • 1970-01-01
      • 2017-03-17
      • 1970-01-01
      • 1970-01-01
      • 2012-03-28
      • 1970-01-01
      • 1970-01-01
      • 2020-03-31
      相关资源
      最近更新 更多