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

相关推荐
t***44233 小时前
MySQL 导出数据
数据库·mysql·adb
翔云1234564 小时前
MySQL主从库复制中,主库如何查找对应日志文件位置
数据库·mysql
Mr_star_galaxy5 小时前
【MySQL基础】视图和权限管理
数据库·mysql
lipiaoshuigood6 小时前
MySQL 数据出海之数据同步方案
数据库·mysql
笨蛋不要掉眼泪7 小时前
Nacos配置中心详解:核心用法、动态刷新与经典面试题解析
java·数据库·后端
@@神农7 小时前
PostgreSQL-SQL语句的执行过程(一)
数据库·sql·postgresql
Andy Dennis8 小时前
一文漫谈数据库存储之索引(B+, B-link, LSM tree等)
数据库·b+树·lsm-tree
CHANG_THE_WORLD8 小时前
字符串定义的汇编分析
汇编·数据库
数据知道8 小时前
PostgreSQL:如何通过progres_fdw跨库关联查询?
数据库·postgresql
v***57009 小时前
MYSQL 创建索引
数据库·mysql