根据 postgresql 中 json 对象的键从 jsonb 类型列中删除 json 对象
Delete json object from jsonb type column based on key of json object in postgresql
任何人都可以告诉我查询以根据存储在 json 对象中的给定 ID 从 jsonb 类型列中的数组中删除整个 json 对象。
示例:我在 t1 table 中有数据列。数据列的类型是 jsonb。
数据栏记录如下
"type" : "users",
"info" : [
{
"id":1,
"name" : "user1"
},
{
"id":2,
"name" : "user2"
}
]
}
现在我想删除 ID = 1 的整个 json 对象(我想通过 json 对象 ID 来识别对象)
预期结果是
{
"type" : "users",
"info" : [
{
"id":2,
"name" : "user2"
}
]
}
请帮我解答一下。
提前致谢
您需要为 jsonb_array_elements
that are then aggregated back to an array 上的每一行使用子查询:
UPDATE t1
SET data = jsonb_set(data, '{info}', (
SELECT COALESCE(jsonb_agg(element), '[]'::jsonb)
FROM jsonb_array_elements(data -> 'info') element
WHERE element ->> 'id' <> '1'
))
##这是解决上述问题的简单查询##
update t1 set data = jsonb_set(data,'{info}',jsonb_path_query_array(data,'$.info[*]?(@."id" != 1)'));
任何人都可以告诉我查询以根据存储在 json 对象中的给定 ID 从 jsonb 类型列中的数组中删除整个 json 对象。
示例:我在 t1 table 中有数据列。数据列的类型是 jsonb。 数据栏记录如下
"type" : "users",
"info" : [
{
"id":1,
"name" : "user1"
},
{
"id":2,
"name" : "user2"
}
]
}
现在我想删除 ID = 1 的整个 json 对象(我想通过 json 对象 ID 来识别对象)
预期结果是
{
"type" : "users",
"info" : [
{
"id":2,
"name" : "user2"
}
]
}
请帮我解答一下。 提前致谢
您需要为 jsonb_array_elements
that are then aggregated back to an array 上的每一行使用子查询:
UPDATE t1
SET data = jsonb_set(data, '{info}', (
SELECT COALESCE(jsonb_agg(element), '[]'::jsonb)
FROM jsonb_array_elements(data -> 'info') element
WHERE element ->> 'id' <> '1'
))
##这是解决上述问题的简单查询##
update t1 set data = jsonb_set(data,'{info}',jsonb_path_query_array(data,'$.info[*]?(@."id" != 1)'));