我正在寻找 psql 查询来更新 my_table 中 jsonb 列内的 jsonb 属性值。 my_table 如下所示,其中“详细信息”是 jsonb:
production_id | uuid
deleted | boolean
details | jsonb
详细示例数据为:
{
"id": "V_12345",
"cars": [
{
"id": "b_1111",
"type": "SportsCar",
"lauches": [
{
"id": S_2112,
"year": 2024,
"nextUpdate": "2024"
}
]
},
{
"id": "c_222",
"type": "PickupTruck",
"lauches": [
{
"id": P_2113,
"year": 2024,
"nextUpdate": "2025"
}
]
}
]
}
如何更新以下匹配的details-->cars[i]-->launches-->'nextUpdate'的值:其中details-->id='V_12345' and cars-->id='b_1111'和汽车-->'type'='SportsCar'
这可以在
jsonb_set
、jsonb_agg
和 jsonb_build_object
的帮助下完成:
UPDATE my_table
SET details = jsonb_set(details, '{cars}', s.cars)
FROM (
SELECT jsonb_agg(
jsonb_build_object(
'id', cars ->> 'id',
'type', cars ->> 'type',
'lauches', CASE WHEN cars ->> 'type' = 'SportsCar' THEN
jsonb_set(cars -> 'lauches', '{0,nextUpdate}', '"NEW_VALUE"')
ELSE cars -> 'lauches' END
)
) as cars
FROM my_table
CROSS JOIN jsonb_array_elements(details->'cars') as cars
WHERE details->>'id' = 'V_12345'
) s;
jsonb_array_elements()
将数组 cars 扩展为每个元素一行。
jsonb_set()
替换每个元素的值。当条件成立时
jsonb_agg()
将元素重新聚合到一个新数组中。