可以在Postgres的JSONB列中的任何键中查找给定值吗? In the documentation我无法看到任何例子。
JSONB
列的示例值:
{
a: 1,
b: 2,
c: 3
}
我想在任何地方找到1
作为值的所有记录。注意:目前可能还有其他密钥而不是a, b, c
。
答案 0 :(得分:4)
use jsonb_each_text
的值,基于以前的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)
答案 1 :(得分:1)
使用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)
答案 2 :(得分:0)
也许迟到了,但这对我有帮助:
with my_data(id, jdata) as (
values
(1, '{ "a": 4, "b": 5}'::jsonb),
(2, '{ "a": 1, "b": 2}'::jsonb),
(3, '{ "x": {"y": 3, "z": 1}}'::jsonb),
(4, '{ "a": [2,1,4]}'::jsonb),
(5, '{ "a": [{"x": 2}, {"y": 1}, {"z": 2}]}'::jsonb)
)
select id, jdata
from my_data
where jdata @? '$.** ? (@ == 1)';
id | jdata
----+---------------------------
2 | { "a": 1, "b": 2 }
3 | { "x": { "y": 3, "z": 1 } }
4 | { "a": [2, 1, 4] }
5 | { "a": [ { "x": 2 }, { "y": 1 }, { "z": 2 } ] }
(4 rows)