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

相关推荐
@PHARAOH12 分钟前
WHAT - SQLite 数据库
数据库·oracle·sqlite
四维碎片20 分钟前
【Qt】乌班图安装Qt环境
开发语言·数据库·qt
wuyunhang12345629 分钟前
MySQL----触发器
数据库·mysql
ptc学习者43 分钟前
OGG 安装注意事项
java·开发语言·数据库
鸽鸽程序猿1 小时前
【MySQL】索引
数据库·mysql
zym大哥大2 小时前
Redis-Zest
数据库·redis·缓存
zl9798992 小时前
Redis-stream、bitfield类型
数据库·redis·缓存
数据库那些事儿2 小时前
Qoder + ADB Supabase :5分钟GET超火AI手办生图APP
数据库·后端
IvorySQL2 小时前
PostgreSQL 18 异步 I/O(AIO)调优指南
数据库·postgresql
kakacc:2 小时前
记录一次巧妙的SQL:一对多关联导致的 sum () 、count()等group函数重复计算问题
数据库·sql