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

相关推荐
独泪了无痕5 小时前
一文搞懂MyBatis中的TypeHandler
数据库·后端·mybatis
三体世界7 小时前
Mysql基本使用语句(一)
linux·开发语言·数据库·c++·sql·mysql·主键
Giser探索家7 小时前
低空智航平台技术架构深度解析:如何用AI +空域网格破解黑飞与安全管控难题
大数据·服务器·前端·数据库·人工智能·安全·架构
chillxiaohan8 小时前
GO学习记录五——数据库表的增删改查
数据库·学习·golang
thulium_8 小时前
使用 Docker 部署 PostgreSQL
docker·postgresql·容器
一颗星的征途10 小时前
java循环分页查询数据,任何把查询到的数据,分批处理,多线程提交到数据库清洗数据
java·数据库·mysql·spring cloud
NightReader11 小时前
如何解决WordPress数据库表损坏导致的错误
数据库
Warren9812 小时前
MySQL,Redis重点面试题
java·数据库·spring boot·redis·mysql·spring·蓝桥杯
青鱼入云13 小时前
mysql查询中的filesort是指什么
数据库·mysql
开航母的李大13 小时前
Navicat 全量&增量数据库迁移
数据库·oracle