【问题标题】:POSTGRESQL: Join columnsPOSTGRESQL:加入列
【发布时间】:2022-07-02 09:11:11
【问题描述】:

我有一个 POSTGRESQL 版本 12.5 数据库,其中有一个包含三列的表:c_idcolumnacolumnb。三列可以有不同的值。

我需要像这样将它们的值合并到一个对象中:

这是示例数据 我有一个包含 3 列相同类型的表

c_id        columna   columnb
1              a       b
2              c       d
3              x       y

我需要运行一个查询,该查询将像这样连接 columnacolumnb 列:

c_id       merge_column
1             {"columna":a, "columnb": "b"}
2             {"columna":d, "columnb": "d"}
3             {"columna":x, "columnb": "y"}

有什么想法吗?

【问题讨论】:

    标签: sql json postgresql knex.js


    【解决方案1】:

    您可以将整行转换为 JSON,删除 c_id 键:

    select t.c_id, to_jsonb(t) - 'c_id' as merge_column
    from the_table t
    

    如果列数比您显示的多,并且您只想获取其中两个,则使用jsonb_build_object() 可能更容易:

    select t.c_id, 
           jsonb_build_object('columna', t.columna, 'columnb', t.columnb) as merge_column
    from the_table t
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多