我有在 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'];
该查询将返回该行,因为它找到了 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。我想要 1 行的 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
关于json - PostgreSQL - 在一列中返回 jsonb 键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43864643/