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

相关推荐
LUCIAZZZ1 小时前
简单的SQL语句的快速复习
java·数据库·sql
Elastic 中国社区官方博客3 小时前
使用真实 Elasticsearch 进行高级集成测试
大数据·数据库·elasticsearch·搜索引擎·全文检索·jenkins·集成测试
@_@哆啦A梦3 小时前
Redis 基础命令
java·数据库·redis
fajianchen3 小时前
MySQL 索引存储结构
数据库·mysql
想做富婆3 小时前
oracle: 多表查询之联合查询[交集intersect, 并集union,差集minus]
数据库·oracle·联合查询
xianwu5435 小时前
反向代理模块jmh
开发语言·网络·数据库·c++·mysql
Leven1995275 小时前
Flink (十三) :Table API 与 DataStream API 的转换 (一)
数据库·sql·flink
geovindu5 小时前
neo4j-community-5.26.0 create new database
数据库·mysql·neo4j
因特麦克斯6 小时前
索引的底层数据结构、B+树的结构、为什么InnoDB使用B+树而不是B树呢
数据库
java1234_小锋7 小时前
说说Redis的内存淘汰策略?
数据库·redis·缓存