我有一个名为 attr 字段的 jsonb 类型,其中包含以下内容:
{
"pid": 1,
"name": "john",
"is_default": true
}
Run Code Online (Sandbox Code Playgroud)
如何将 is_default 更改为 false?
我试着跑到下面,但没有成功。
update attr set attr ->> 'is_default' = false where sales_type = 2
Run Code Online (Sandbox Code Playgroud)
小智 26
有两种方法可以实现此目的:
只需连接新的键/值对:
update the_table
set attr = attr || '{"is_default": false}';
Run Code Online (Sandbox Code Playgroud)
这是有效的,因为当连接两个jsonb
值时,现有的键将被覆盖。
另一种方法是使用jsonb_set()
它更新通过“路径”指定的位置处的值(通过数组的元素定义)
update the_table
set attr = jsonb_set(attr, array['is_default'], to_jsonb(false));
Run Code Online (Sandbox Code Playgroud)
如果您使用的是版本 14(2021 年 9 月发布)或更高版本,您可以将其简化为:
update the_table
set attr['is_default'] = to_jsonb(false);
Run Code Online (Sandbox Code Playgroud)
Ali*_*jad 10
假设我们得到了这个jsonb
{
"animals": [
{"name": "Cat", "age": 5},
{"name": "Dog", "age": 10}
]
}
Run Code Online (Sandbox Code Playgroud)
我们想要将年龄Cat
从 5 更新到 15。该函数jsonb_set(...)
返回一个具有更新值的新 jsonb。
select
jsonb_set(
'{"animals": [{"name": "Cat", "age": 5}, {"name": "Dog", "age": 10}]}',
'{animals,0,age}', -- Path to the field to update
'15'::jsonb, -- New value to set
false -- If true, this will make a new key if it doesn't exist in the jsonb
)
;
Run Code Online (Sandbox Code Playgroud)
如果您想在 SQL 更新中执行类似的操作,则如下所示:
update animals
set
animals_metadata = jsonb_set(animals_metadata, '{animals,0,age}', to_jsonb(15), false)
where id = '123';
Run Code Online (Sandbox Code Playgroud)
查看官方文档了解更多!
归档时间: |
|
查看次数: |
54753 次 |
最近记录: |