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

相关推荐
IT项目管理1 小时前
达梦数据库DMHS介绍及安装部署
linux·数据库
你都会上树?1 小时前
MySQL MVCC 详解
数据库·mysql
大春儿的试验田1 小时前
高并发收藏功能设计:Redis异步同步与定时补偿机制详解
java·数据库·redis·学习·缓存
Ein hübscher Kerl.2 小时前
虚拟机上安装 MariaDB 及依赖包
数据库·mariadb
醇醛酸醚酮酯2 小时前
Qt项目锻炼——TODO清单(二)
开发语言·数据库·qt
GreatSQL社区3 小时前
用systemd管理GreatSQL服务详解
数据库·mysql·greatsql
掘根3 小时前
【MySQL进阶】错误日志,二进制日志,mysql系统库
数据库·mysql
weixin_438335403 小时前
基础知识:mysql-connector-j依赖
数据库·mysql
小明铭同学3 小时前
MySQL 八股文【持续更新ing】
数据库·mysql
Mr_Xuhhh3 小时前
信号与槽的总结
java·开发语言·数据库·c++·qt·系统架构