PostgreSQL-在一列中返回jsonb键

PostgreSQL-在一列中返回jsonb键,json,postgresql,jsonb,Json,Postgresql,Jsonb,我有在jsonb列中搜索id的查询,数组可以包含许多id 假设我有这样的数据 id | act | act_id | from_ids | object_ids | post_date 2 post 1 {"2":"1494308197","3":"1494308198","4":"1494308199"} {"items":["104564"]} 14943081

我有在jsonb列中搜索id的查询,数组可以包含许多id

假设我有这样的数据

id | act | act_id |                    from_ids                         |    object_ids       | post_date
2    post      1    {"2":"1494308197","3":"1494308198","4":"1494308199"}  {"items":["104564"]}   1494308197
SELECT an.*
FROM activity_network an
WHERE an.from_ids ?| ARRAY['2','3'];
像这样的问题

id | act | act_id |                    from_ids                         |    object_ids       | post_date
2    post      1    {"2":"1494308197","3":"1494308198","4":"1494308199"}  {"items":["104564"]}   1494308197
SELECT an.*
FROM activity_network an
WHERE an.from_ids ?| ARRAY['2','3'];
该查询将返回该行,因为它找到2和3。但是我如何才能返回它在自己的列中找到的内容呢。因此,它在结果中以文本或json格式或类似的格式返回2,3

我试过这个

SELECT an.*, jsonb_each_text(from_ids) b
FROM activity_network an
WHERE an.from_ids ?| ARRAY['2','3'];
但这将创建3行,其中包含一个b列,每个行的值分别为2、3和4。我想要一行,b列包含2和3,这就是我搜索的内容

可能吗

我正在寻找的示例结果。请注意最后一列。为了演示的目的,我把它作为分隔的列。它可以是我可以使用的任何格式

2 | post | 1 | {"2":"1494308197","3":"1494308198","4":"1494308199} | {"items":["104564"]} | 1494308197 | 2,3}

在这里我爆炸/内爆它。非常难看的方式

t=# with p as (
  with c as (
    select '{"2":"1494308197","3":"1494308198","4":"1494308199"}'::json j
  )
  select json_object_keys(j),j->json_object_keys(j) v
  from c
)
select concat('{',string_agg(concat('"',json_object_keys,'"',':',v)::text,','),'}')::json
from p
where json_object_keys::int = ANY (ARRAY [2,4]);
               concat
-------------------------------------
 {"2":"1494308197","4":"1494308199"}
(1 row)

Time: 0.348 ms

函数
jsonb\u exists\u all
听起来像您想要的。它要求数组中的所有元素都作为顶级键存在于对象中

您可以使用psql中的
\df*jsonb*
命令找到该函数和其他未记录的jsonb函数

粘贴示例:

test=# SELECT * from twj WHERE jsonb_exists_any(from_ids, ARRAY['2','3']);
 id | act  |                         from_ids                          
----+------+-----------------------------------------------------------
  1 | post | {"2": "1494308197"}
  3 | post | {"2": "1494308197", "3": "1494308198", "4": "1494308199"}
(2 rows)

test=# SELECT * from twj WHERE jsonb_exists_all(from_ids, ARRAY['2','3']);
 id | act  |                         from_ids                          
----+------+-----------------------------------------------------------
  3 | post | {"2": "1494308197", "3": "1494308198", "4": "1494308199"}
(1 row)

您使用的
?|
操作符调用
jsonb_exists_any
函数。

您希望仅显示带有键2和键3的json,并使用键4-right?。是的,因此,例如,我有一个ID数组,我在其中搜索,本例为2和3,jsonb字段也包含带有键4的键。但我只想知道查询找到的记录的ID,在本例中是2和3。@VaoTsun我添加了一个示例预期结果。