给定以下行jsonb
列details
。如何编写查询,以便选择键名以_col
结尾且值为B
的记录。所以带有ID 1,2的记录。
id | details
1 | { "one_col": "A", "two_col": "B" }
2 | { "three_col": "B" }
3 | { another: "B" }
到目前为止,我只是根据价值找到匹配方式,而不是关键。
答案 0 :(得分:1)
使用函数jsonb_each_text()
,它将json对象作为成对(key, value)
:
with the_data(id, details) as (
values
(1, '{ "one_col": "A", "two_col": "B" }'::jsonb),
(2, '{ "three_col": "B" }'),
(3, '{ "another": "B" }')
)
select t.*
from the_data t,
lateral jsonb_each_text(details)
where key like '%_col'
and value = 'B';
id | details
----+----------------------------------
1 | {"one_col": "A", "two_col": "B"}
2 | {"three_col": "B"}
(2 rows)