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

相关推荐
施嘉伟10 分钟前
Oracle 11g RAC ASM磁盘组剔盘、加盘实施过程
数据库·oracle
橘猫云计算机设计1 小时前
springboot基于hadoop的酷狗音乐爬虫大数据分析可视化系统(源码+lw+部署文档+讲解),源码可白嫖!
数据库·hadoop·spring boot·爬虫·python·数据分析·毕业设计
卓怡学长2 小时前
w304基于HTML5的民谣网站的设计与实现
java·前端·数据库·spring boot·spring·html5
冰^2 小时前
MySQL VS SQL Server:优缺点全解析
数据库·数据仓库·redis·sql·mysql·json·数据库开发
电商数据girl2 小时前
产品经理对于电商接口的梳理||电商接口文档梳理与接入
大数据·数据库·python·自动化·产品经理
Spring小子3 小时前
黑马点评商户查询缓存--缓存更新策略
java·数据库·redis·后端
溜溜刘@♞5 小时前
数据库之mysql优化
数据库·mysql
uwvwko5 小时前
ctfhow——web入门214~218(时间盲注开始)
前端·数据库·mysql·ctf
柯3495 小时前
Redis的过期删除策略和内存淘汰策略
数据库·redis·lfu·lru
Tiger_shl6 小时前
【Python语言基础】24、并发编程
java·数据库·python