查询匹配JSONB列的行,其中键以名称结束,键值是特定值

时间:2017-01-20 23:31:14

标签: postgresql jsonb

给定以下行jsonbdetails。如何编写查询,以便选择键名以_col结尾且值为B的记录。所以带有ID 1,2的记录。 id | details 1 | { "one_col": "A", "two_col": "B" } 2 | { "three_col": "B" } 3 | { another: "B" }

到目前为止,我只是根据价值找到匹配方式,而不是关键。

1 个答案:

答案 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)