Update column contains JSON with some value from another column

时间:2019-04-08 13:00:23

标签: postgresql

There is some table with columns A and B. A column contains only numbers (for example: 100, 200, 300, etc.). B column contains JSON values like:

{"First": "0", "Second": "1"}

There are a lot of rows. How to update B column JSON values with values of A column using SQL query? For example, to make JSON look like:

{"First": "100", "Second": "1"}

{"First": "200", "Second": "1"}

{"First": "300", "Second": "1"}

1 个答案:

答案 0 :(得分:1)

Sounds like a strange thing to do. In general you shouldn't duplicate data in a relational database.

But nevertheless, this is possible:

update the_table
   set b = jsonb_set(b, array['First'], to_jsonb(a), true);

This will only change existing First keys. If First does not exist, it will be created.

Online example: https://rextester.com/RGNO64902