将专栏作为键移动到JSONB字段

发布于 2025-01-21 02:40:25 字数 480 浏览 4 评论 0原文

我正在使用Postgres数据库,并有一个表面,如下所示,

id    firstname    lastname  settings
 1     Sam          Crews    {"some_key": some_value}
 2     John         Dave     {"some_key": some_value}

我正在尝试将其中一列移动到设置JSON并删除列。因此,

id    firstname      settings
 1     Sam           {"some_key": some_value, "lastname": "Crews"}
 2     John          {"some_key": some_value, "lastname": "Dave"}

在JSONB字段中移动列的Postgres语法是什么?一直在搜索,但似乎无法弄清楚。

I'm using Postgres database and have a table like below

id    firstname    lastname  settings
 1     Sam          Crews    {"some_key": some_value}
 2     John         Dave     {"some_key": some_value}

I am trying to move one of the columns into settings json and drop the column. So it becomes,

id    firstname      settings
 1     Sam           {"some_key": some_value, "lastname": "Crews"}
 2     John          {"some_key": some_value, "lastname": "Dave"}

What is the postgres syntax for moving column to in jsonb field? Been searching but can not seem to figure it out.

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

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

发布评论

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

评论(1

相对绾红妆 2025-01-28 02:40:25

您需要运行更新以将键/值对添加到现有 JSON 值。

update the_table 
   set settings = settings||jsonb_build_object('lastname', lastname)

如果settings 可能为空,您可以使用coalesce()

update the_table 
   set settings = coalesce(settings, '{}) || jsonb_build_object('lastname', lastname)

然后您可以删除该列

alter table the_table
  drop column lastname;

但这听起来像是一个坏主意。从长远来看,为什么要让这种现象变得非正常化,让你的生活变得更加困难呢?

You need to run an update to add the key/value pair to the existing JSON value.

update the_table 
   set settings = settings||jsonb_build_object('lastname', lastname)

if it's possible that settings is null, you can e.g. use coalesce()

update the_table 
   set settings = coalesce(settings, '{}) || jsonb_build_object('lastname', lastname)

then you can drop the column

alter table the_table
  drop column lastname;

But this sounds like a bad idea. Why de-normalize this and make your life harder in the long run?

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