我在表的jsonb value
列中有一个看起来像这样的对象数组:
"west": [
{"id": "aa92f346-7a93-4443-949b-4eab0badd983", "version": 1},
{"id": "cd92e346-6b04-3456-050a-5eeb0bddd027", "version": 3}
]
我的目标是根据ID和版本从这个数组中删除某些对象:
SELECT value::jsonb #- '{west, 1}' FROM game.settings;
但是,1
不应该是硬编码的,而是应该等于数组中对象的位置,该位置与我查找的id和版本匹配(在这种情况下{{1} }})。
我如何确定此阵列位置并将其传递到我目前持有的硬编码"id": "cd92e346-6b04-3456-050a-5eeb0bddd027", "version": 3
的位置?
答案 0 :(得分:5)
示例数据:
create temp table settings as
select
'{"west": [
{"id": "aa92f346-7a93-4443-949b-4eab0badd983", "version": 1},
{"id": "cd92e346-6b04-3456-050a-5eeb0bddd027", "version": 3}
]}'::jsonb as value;
您可以使用jsonb_array_elements() with ordinality
来确定给定元素的数组位置:
select elem, position
from settings, jsonb_array_elements(value->'west') with ordinality arr(elem, position)
where elem->>'id' = 'cd92e346-6b04-3456-050a-5eeb0bddd027';
elem | position
--------------------------------------------------------------+----------
{"id": "cd92e346-6b04-3456-050a-5eeb0bddd027", "version": 3} | 2
(1 row)
使用position
从阵列中删除对象:
select value #- array['west', (position- 1)::text] new_value
from settings, jsonb_array_elements(value->'west') with ordinality arr(elem, position)
where elem->>'id' = 'cd92e346-6b04-3456-050a-5eeb0bddd027';
new_value
--------------------------------------------------------------------------
{"west": [{"id": "aa92f346-7a93-4443-949b-4eab0badd983", "version": 1}]}
(1 row)