按值删除jsonb数组元素

编程入门 行业动态 更新时间:2024-10-26 14:36:56
本文介绍了按值删除jsonb数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我确实弄清楚了如何从单个记录的数组中删除一个值,但是如何对其中的许多记录执行删除操作.问题在于我如何使用子查询.由于它只返回单个元素.也许我的方法是错误的.

I did figure out how to remove a value from an array for a single record, but how to do it for many of them. The problem is in the way how I use the subquery. As it has to return only single element. Maybe my approach is wrong.

Given input: '{attributes:['is_new', 'is_old']}' Expected result '{attributes: ['is_old']}' #remove 'is_new' from jsonb array

Real example: # sku | properties # -------+-------------------------------- # nu3_1 | { + # | "name": "silly_hodgkin", + # | "type": "food", + # | "attributes": [ + # | "is_gluten_free", + # | "is_lactose_free", + # | "is_new" + # | ] + # | }

#Query that removes single array element: SELECT c.sku, jsonb_agg(el) FROM catalog c JOIN (select sku, jsonb_array_elements_text(properties->'attributes') as el from catalog) c2 ON c.sku=c2.sku where el 'is_new' GROUP BY c.sku;

#Update query that removes single array element in single record UPDATE catalog SET properties=jsonb_set(properties, '{attributes}', ( SELECT jsonb_agg(el) FROM catalog c JOIN (select sku, jsonb_array_elements_text(properties->'attributes') as el from catalog) c2 ON c.sku=c2.sku WHERE el 'is_new' AND c.sku='nu3_1' GROUP BY c.sku ) ) WHERE sku='nu3_1';

问题又来了.如何按值删除许多数据库记录的jsonb数组元素?

The question again is. How to remove jsonb array element by value for many database records?

推荐答案

使用 jsonb_set()和删除运算符- :

Use jsonb_set() and the delete operator -:

update catalog set properties = jsonb_set(properties, '{attributes}', (properties->'attributes') - 'is_new');

在rextester中对其进行测试.

更多推荐

按值删除jsonb数组元素

本文发布于:2023-10-23 18:58:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1521725.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   元素   jsonb

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!