在 PostgreSQL 中,从 JSONB 数组 select 一个对象的最佳方法是什么?
In PostgreSQL, what's the best way to select an object from a JSONB array?
现在,我有一个数组,我可以 select 关闭 table。
[{"_id": 1, "count: 3},{"_id": 2, "count: 14},{"_id": 3, "count: 5}]
据此,我只需要特定 _id 的计数。例如,我需要
的计数
_id: 3
我已经阅读了文档,但我一直无法找出获取对象的正确方法。
WITH test_array(data) AS ( VALUES
('[
{"_id": 1, "count": 3},
{"_id": 2, "count": 14},
{"_id": 3, "count": 5}
]'::JSONB)
)
SELECT val->>'count' AS result
FROM
test_array ta,
jsonb_array_elements(ta.data) val
WHERE val @> '{"_id":3}'::JSONB;
结果:
result
--------
5
(1 row)
现在,我有一个数组,我可以 select 关闭 table。
[{"_id": 1, "count: 3},{"_id": 2, "count: 14},{"_id": 3, "count: 5}]
据此,我只需要特定 _id 的计数。例如,我需要
的计数_id: 3
我已经阅读了文档,但我一直无法找出获取对象的正确方法。
WITH test_array(data) AS ( VALUES
('[
{"_id": 1, "count": 3},
{"_id": 2, "count": 14},
{"_id": 3, "count": 5}
]'::JSONB)
)
SELECT val->>'count' AS result
FROM
test_array ta,
jsonb_array_elements(ta.data) val
WHERE val @> '{"_id":3}'::JSONB;
结果:
result
--------
5
(1 row)