Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Postgresql 筛选值上的Postgres jsonb字段,仅返回匹配的键值对_Postgresql_Jsonb - Fatal编程技术网

Postgresql 筛选值上的Postgres jsonb字段,仅返回匹配的键值对

Postgresql 筛选值上的Postgres jsonb字段,仅返回匹配的键值对,postgresql,jsonb,Postgresql,Jsonb,我有一些数据的结构大致如下: id | data 1 | {"a": 4, "b": 5, "c": 19} 2 | {"a": 6, "b": 7} 3 | {"a": 8, "d": 3} 4 | {"a": 3, "b": 1} 我希望能够根据json中键的值过滤这些数据。正如您所看到的,记

我有一些数据的结构大致如下:

id  | data

1   | {"a": 4, "b": 5, "c": 19}
2   | {"a": 6, "b": 7}
3   | {"a": 8, "d": 3}
4   | {"a": 3, "b": 1}
我希望能够根据json中键的值过滤这些数据。正如您所看到的,记录之间的键可能会有所不同。例如,我想获得每行值大于4的所有键值对。对于上述数据,应给出:

id  | data
1   | {"b": 5, "c": 19}
2   | {"a": 6, "b": 7}
3   | {"a": 8}
4   | {} (for this row, it's fine if it's just left out, or returned as empty object)

我一直在寻找类似于提供的答案,但我不想提供一个特定的字段名。另外,如果条件成立,我希望同时获得键和值。这是我第一次使用Postgres jsonb,因此我可能缺少一个函数。

您需要将
jsonb_each()
与子查询一起使用:

select d.id, t.new_data
from the_table d 
  cross join lateral (
     select jsonb_object_agg(key, value) as new_data
     from jsonb_each(d.data) as x(key, value)
     where value::int > 4
  ) as t

您需要将
jsonb_each()
与子查询一起使用:

select d.id, t.new_data
from the_table d 
  cross join lateral (
     select jsonb_object_agg(key, value) as new_data
     from jsonb_each(d.data) as x(key, value)
     where value::int > 4
  ) as t