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

相关推荐
Kaede63 分钟前
如何保护MySQL中的重要数据
数据库·mysql
小股虫6 分钟前
Redis实现轻量级消息队列:实操手册与项目应用指南
数据库·redis
lllsure10 分钟前
【MySQL】数据库备份与恢复
数据库·mysql
ttthe_MOon14 分钟前
MySQL 高阶查询语句:子查询、连接查询与多表关联
数据库·sql
天下无敌笨笨熊26 分钟前
kotlin函数式编程
开发语言·数据库·kotlin
SHIPKING39334 分钟前
【开发策略】MCP 多表查询策略方案
数据库·oracle
kka杰40 分钟前
MYSQL 事务-1
数据库·mysql·oracle
chian_ocean1 小时前
在 KubeSphere 上部署 AI 大模型 Ollama
数据库
跟着珅聪学java1 小时前
Jedis SetParams教程:参数化设置 Redis 键值对
数据库·redis·缓存
一颗宁檬不酸1 小时前
数据库开发实战案例分享:从函数到存储过程的应用
数据库·数据库开发