PostgreSQL-如何更改JSONB数据类型?

时间:2018-12-15 12:43:31

标签: postgresql

我有一个表,其中包含错误数据类型的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"}

如果您能指导我如何实现它,我将不胜感激。

1 个答案:

答案 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))