将JSONB数据迁移到列

发布于 2025-01-27 18:38:40 字数 573 浏览 3 评论 0原文

我有一个带有以下模式的PostgreSQL数据库:

CREATE TABLE myrecords (data JSONB);

它具有一些看起来像这样的记录:

                    data                     
---------------------------------------------
 {"field1": "enabled", "field2": "disabled"}

我想将数据从JSON BLOB迁移到SQL列;我像这样更改了表:

ALTER TABLE myrecords ADD COLUMN field1 BOOLEAN;
ALTER TABLE myrecords ADD COLUMN field2 BOOLEAN;

我设法使用jsonb_to_record将JSON对象转换为行,但是我不知道如何(a)转换“启用”/“ disabled”字符串文字以布尔值为true/false值,(b)更新行以设置新的列值。是否可以同时更新一行?

I have a PostgreSQL database with the following schema:

CREATE TABLE myrecords (data JSONB);

It has some records that look like this:

                    data                     
---------------------------------------------
 {"field1": "enabled", "field2": "disabled"}

I'd like to migrate the data from a JSON blob to SQL columns; I altered the table like so:

ALTER TABLE myrecords ADD COLUMN field1 BOOLEAN;
ALTER TABLE myrecords ADD COLUMN field2 BOOLEAN;

I've managed to convert the JSON object to a row using jsonb_to_record, but I can't figure out how to (a) convert the "enabled"/"disabled" string literals to BOOLEAN TRUE/FALSE values, and (b) update the row to set the new column values. Is it possible to update a row while at the same time selecting data from it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

吾性傲以野 2025-02-03 18:38:40

您可以使用- >>然后将结果比较以获取布尔值:

update myrecords
  set field1 = (data ->> 'field1') = 'enabled',
      field2 = (data ->> 'field2') = 'enabled'
;

You can use ->> then compare the result to get a boolean value:

update myrecords
  set field1 = (data ->> 'field1') = 'enabled',
      field2 = (data ->> 'field2') = 'enabled'
;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文