我正试图从我的数据库中删除一个元素。我要删除的元素位于一个名为 playerContainer 的 JSON 对象中,该对象包含一个名为 players 的数组。这一切都位于一个名为 site_content 的表中。我试图根据对象的 ID 删除该对象,但出现此错误。
DELETE elem from site_content, lateral jsonb_array_elements(content->'playersContainer'->'players') elem where elem @> '{"id":"22"}'
because: ERROR: syntax error at or near "elem" Position: 27
下面是我的查询,谁能看出我哪里出错了?
DELETE elem
from site_content,
lateral jsonb_array_elements(content->'playersContainer'->'players') elem
where elem @> '{"id":"1"}'
这是示例 JSON
"playersContainer": {
"players": [
{
"id": "1",
"name": "Nick",
"teamName": "Shire Soldiers",
"ratings": [
1,
5,
6,
9
],
"assists": 17,
"manOfTheMatches": 20,
"cleanSheets": 1,
"data": [
3,
2,
3,
5,
6
],
"totalGoals": 19
},
}
最佳答案
DELETE适用于表格的行。因此,除非您想删除整行,否则不能使用它。
试试这个:
create temp table testing as
select
'{ "playersContainer": {
"players": [
{
"id": "1",
"name": "Nick"
},
{
"id": "2",
"name": "Rick"
},
{
"id": "3",
"name": "Trick"
}
]
}}'::jsonb as value;
现在您需要找到要移除的玩家的位置,假设您想要 ID 为 2 的 Rick(负 1,因为索引从 0 开始)
select position-1 from testing, jsonb_array_elements(value->'playersContainer'->'players') with ordinality arr(elem, position) WHERE elem->>'id' = '2';
现在您可以将其与 UPDATE
语句结合使用来更新字段。使用减号 (-) 运算符删除所需索引处的元素。
UPDATE testing SET value = jsonb_set(value, '{playersContainer,players}', (value->'playersContainer'->'players') - (select position-1 from testing, jsonb_array_elements(value->'playersContainer'->'players') with ordinality arr(elem, position) WHERE elem->>'id' = '2')::int );
最终结果:
{
"playersContainer":{
"players":[
{
"id":"1",
"name":"Nick"
},
{
"id":"3",
"name":"Trick"
}
]
}
}
关于postgresql - 从对象 JSONB 中的数组中删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42299061/