首页 > 解决方案 > Postgres:如何在不知道键的情况下搜索 json 类型列中对象的 _all_ 字段上的值

问题描述

在 Postgres 数据库中,我有一个 jsonb 类型的列,其中包含一个我无法预测其键的通用对象:

{"some_key":"value", "another_unpredictable_key":"another value}

是否可以在不知道键的情况下在所有字段中搜索特定值?某事。喜欢

select * from ... where column_whatever->>'*' = '...'

标签: sqljsonpostgresql

解决方案


您需要将 json 值转换为多行(键/值对)并在结果中搜索:

select * 
from some_table t 
where exists (select * 
              from jsonb_each_text(t.jsonb_column) as x(ky,val)
              where x.val = 'some value');

jsonb_each_text()为每个顶级键/值对返回一行。这不处理嵌套键。


推荐阅读