Postgresql 删除数组中的元素

extra为 {"a": [null, 3, null],"b": 111} 使用sql 将extra中a中的null移除

第一步:

首先先把[null, 3, null]移除,

sql 复制代码
select json_agg(elem) filter ( where elem != 'null' )
from (select jsonb_array_elements('[null,3,null]'::jsonb) as elem) t;

这将得到[3]

  1. jsonb_array_elements 会展开 extra 中 a 数组的每个元素。
  2. filter ( where elem != 'null' ) 用于过滤掉 null。
  3. 使用 jsonb_agg 将非 null 的值重新聚合为一个数组。

第二步:

使用jsonb_set更新数据

sql 复制代码
update table_name
SET extra = jsonb_set(extra::jsonb, '{a}', (select json_agg(elem)
                                            from jsonb_array_elements((extra -> 'a')::jsonb) as elem
                                            where elem != 'null')::jsonb)
where extra::jsonb ? 'a';

更多json用法:

http://www.postgres.cn/docs/12/functions-json.html

相关推荐
27669582928 小时前
最新 _rand 分析
前端·javascript·数据库·node·rand·231滑块·_rand分析
一 乐8 小时前
宠物医院预约|宠物医院|基于SprinBoot+vue的宠物医院预约管理系统源码+数据库+文档)
java·前端·数据库·vue.js·后端·springboot
蟹至之8 小时前
【MySQL】视图
数据库·mysql·视图
Fuly10248 小时前
langchain基础教程(6)---构建知识库--①向量数据库-chromadb
数据库·langchain
橘子编程9 小时前
仓颉语言:华为新一代编程利器
java·c语言·开发语言·数据库·python·青少年编程
i***39589 小时前
开放自己本机的mysql允许别人连接
数据库·mysql·adb
n***F8759 小时前
【MySQL】视图
数据库·mysql·oracle
p***93039 小时前
使用Django Rest Framework构建API
数据库·django·sqlite
r***12389 小时前
mysql怎么查看
数据库·mysql
zs宝来了9 小时前
Redis的String 底层实现
数据库·redis·缓存