Pra*_*oni 5 postgresql jsonb postgresql-9.6
我有一个这种格式的 jsonb 列。
{
"categoryList": [{
"category_menu_id": "51",
"is_featured_product": 0
}, {
"category_menu_id": "54",
"is_featured_product": 1
}]
}
Run Code Online (Sandbox Code Playgroud)
如何通过 category_menu_id 删除类别?
这个选择查询通过 category_menu_id 工作正常。
select product_category
from product
where product_category->'categoryList' @> '[{"category_menu_id": "51"}]';
Run Code Online (Sandbox Code Playgroud)
示例数据(请注意,我添加了主键id
以启用更新表):
create table product(id int primary key, product_category jsonb);
insert into product values
(1,
'{
"categoryList": [{
"category_menu_id": "51",
"is_featured_product": 0
}, {
"category_menu_id": "54",
"is_featured_product": 1
}]
}');
Run Code Online (Sandbox Code Playgroud)
"category_menu_id": "51"
此查询跳过json 数组中的元素:
select jsonb_build_object('categoryList', jsonb_agg(value))
from product,
jsonb_array_elements(product_category->'categoryList')
where value->>'category_menu_id' <> '51';
jsonb_build_object
--------------------------------------------------------------------------
{"categoryList": [{"category_menu_id": "54", "is_featured_product": 1}]}
(1 row)
Run Code Online (Sandbox Code Playgroud)
使用上面的查询来更新表:
update product p
set product_category = (
select jsonb_build_object('categoryList', jsonb_agg(value))
from product ps,
jsonb_array_elements(product_category->'categoryList')
where ps.id = p.id -- important! primary key to identify a row
and value->>'category_menu_id' <> '51')
returning *;
id | product_category
----+--------------------------------------------------------------------------
1 | {"categoryList": [{"category_menu_id": "54", "is_featured_product": 1}]}
(1 row)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2988 次 |
最近记录: |