我有一个表,其中包含错误数据类型的jsonb列“ details”,如下所示:
select id,details from products;
id | details
---+-----------------------------------------
1 | {"price": "310", "supplier": "VendorA"}
2 | {"price": "250", "supplier": "VendorB"}
在这里,我想将“价格”的数据类型更改为当前存储为字符串的整数。期望的结果如下:
id | details
---+-----------------------------------------
1 | {"price": 310, "supplier": "VendorA"}
2 | {"price": 250, "supplier": "VendorB"}
如果您能指导我如何实现它,我将不胜感激。
答案 0 :(得分:1)
您可以使用函数to_jsonb()
将值转换为json号:
select id, jsonb_set(details, '{price}', to_jsonb((details->>'price')::int))
from products
id | jsonb_set
----+---------------------------------------
1 | {"price": 310, "supplier": "VendorA"}
2 | {"price": 250, "supplier": "VendorB"}
(2 rows)
更新语句可能如下所示:
update products
set details = jsonb_set(details, '{price}', to_jsonb((details->>'price')::int))