查询行以匹配 JSONB 列,其中键以名称结尾且键值是特定值
Query rows for matching JSONB column where key ends with a name and key value is a specific value
给定以下行 jsonb
列 details
。如何编写查询以便选择键名称以 _col
结尾且值为 B
的记录。因此记录 ID 为 1、2 的记录。
id | details
1 | { "one_col": "A", "two_col": "B" }
2 | { "three_col": "B" }
3 | { another: "B" }
到目前为止,我只找到了根据值而不是键进行匹配的方法。
使用函数 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)
给定以下行 jsonb
列 details
。如何编写查询以便选择键名称以 _col
结尾且值为 B
的记录。因此记录 ID 为 1、2 的记录。
id | details
1 | { "one_col": "A", "two_col": "B" }
2 | { "three_col": "B" }
3 | { another: "B" }
到目前为止,我只找到了根据值而不是键进行匹配的方法。
使用函数 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)