Arrays 按值删除jsonb数组元素

Arrays 按值删除jsonb数组元素,arrays,json,postgresql,jsonb,Arrays,Json,Postgresql,Jsonb,我确实知道如何从一条记录的数组中删除一个值,但是如何为其中的许多记录删除该值。问题在于如何使用子查询。因为它只能返回单个元素。也许我的方法是错误的 Given input: '{attributes:['is_new', 'is_old']}' Expected result '{attributes: ['is_old']}' #remove 'is_new' from jsonb array 问题又来了。如何为许多数据库记录按值删除jsonb数组元素?因此,我相信您要查找的QRY是:

我确实知道如何从一条记录的数组中删除一个值,但是如何为其中的许多记录删除该值。问题在于如何使用子查询。因为它只能返回单个元素。也许我的方法是错误的

Given input: '{attributes:['is_new', 'is_old']}' Expected result '{attributes: ['is_old']}' #remove 'is_new' from jsonb array
问题又来了。如何为许多数据库记录按值删除jsonb数组元素?

因此,我相信您要查找的QRY是:

with q as (
  select distinct sku, jsonb_set(properties,'{attributes}',jsonb_agg(el) over (partition by sku),false) new_properties
  from (
    select 
      sku, jsonb_array_elements_text(properties->'attributes') as el, properties
    from catalog
  ) p
  where el != 'is_new'
)
update catalog set properties = q.new_properties from q where catalog.sku = q.sku
;

请注意,我假设您的sku至少在英国

您的解决方案有效+您向我介绍了一些新功能,如窗口函数,并为我提供了替代解决方案的想法:

以q为例 选择c.sku作为sku,选择jsonb_setproperties,“{attributes}”,选择jsonb_aggel作为新的_属性 从目录c中选择sku,jsonb_数组_元素_文本属性->'attributes'作为el,从目录c2中选择c.sku=c2.sku,其中el!='你是新来的吗 按c.sku分组 更新目录集属性=q.new_属性,从q其中catalog.sku=q.sku; 使用:


中测试它我只是重写了问题qry,这样它就可以工作了。我自己肯定更喜欢-operator,我在这里提问之前尝试了“-”操作符,但它不起作用。使它工作的是括号属性->属性。如果没有他们,这是行不通的。我不明白。有什么区别?我现在明白了'->'和'-'都是运算符。看起来,“-”具有更高的优先级,它试图对两个字符串使用它,这两个字符串无法工作。谢谢@klin.有没有可能在这方面做个调查?假设您在一个数组中有一个ID为的对象,并且执行where ID=1?@NickPocock-是的,您可以像在任何其他UPDATE语句中一样添加where子句,看看类似的内容如何?奋力拼搏!您好,@klin,如果我有一个包含[123345789]内容的字段父字段,我可以用jsonb_集删除一个元素,比如说123,或者有其他解决方案吗? #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';
with q as (
  select distinct sku, jsonb_set(properties,'{attributes}',jsonb_agg(el) over (partition by sku),false) new_properties
  from (
    select 
      sku, jsonb_array_elements_text(properties->'attributes') as el, properties
    from catalog
  ) p
  where el != 'is_new'
)
update catalog set properties = q.new_properties from q where catalog.sku = q.sku
;
update catalog
set properties = 
    jsonb_set(properties, '{attributes}', (properties->'attributes') - 'is_new');