Postgres and jsonb - search value at any key

梦想与她 提交于 2019-12-13 13:15:07

问题


Is possible to look for a given value at any key in a JSONB column in Postgres? In the documentation I can't see any example.

Example value at a JSONB column:

{
  a: 1,
  b: 2,
  c: 3
}

I want to find all records that have 1 as a value anywhere. NOTE: there may be other keys than a, b, c unknown at the moment.


回答1:


use value of jsonb_each_text, sample based on previous sample of McNets,:

t=# select * from json_test join jsonb_each_text(json_test.data) e on true 
where e.value = '1';
 id |                 data                 | key | value
----+--------------------------------------+-----+-------
  1 | {"a": 1}                             | a   | 1
  3 | {"a": 1, "b": {"c": "d", "e": true}} | a   | 1
(2 rows)



回答2:


Use json_each_text():

with my_data(id, jdata) as (
values
    (1, '{ "a": 1, "b": 2, "c": 3}'::json),
    (2, '{ "j": 4, "k": 5, "l": 6}'::json),
    (3, '{ "x": 1, "y": 2, "z": 3}'::json)
)

select id, jdata
from my_data,
lateral json_each_text(jdata) 
where value::int = 1

 id |           jdata           
----+---------------------------
  1 | { "a": 1, "b": 2, "c": 3}
  3 | { "x": 1, "y": 2, "z": 3}
(2 rows)    


来源:https://stackoverflow.com/questions/43739601/postgres-and-jsonb-search-value-at-any-key

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!