【问题标题】:How to combine two postgres columns to single value (json object)如何将两个 postgres 列组合为单个值(json 对象)
【发布时间】:2019-05-28 03:26:52
【问题描述】:

我正在尝试在我的 food.list 表上编写查询:

categories    | items
----------------------------
dairy         | ["milk", "cheese"]
fruit         | ["apples", "pears", "grapes"]
vegetables    | ["carrots"]  

并返回一个包含一行的 selected_foods 列。我希望该行的值是一个具有类别(键)列表和项目(值)数组的对象。

selected_foods
------------------------------------
{ 
  dairy: ["milk", "cheese"], 
  fruit: ["apples", "pears", "grapes"], 
  vegetables: ["carrots"] 
}

到目前为止,我已经尝试过:

SELECT json_agg(json_build_object(categories, items::json))::json 
AS selected_foods
FROM food.list

但这会返回一个对象数组,即:

selected_foods
------------------------------------
[ 
  { dairy: ["milk", "cheese"] }, 
  { fruit: ["apples", "pears", "grapes"] }, 
  { vegetables: ["carrots"] }
]

我认为我太早应用了 json_build_object 函数......或者我可能需要在之后再次打开它们?

任何帮助都会很棒,谢谢:)

【问题讨论】:

    标签: sql arrays json postgresql


    【解决方案1】:

    使用json_object_agg

    SELECT json_object_agg( categories, items::json)  as selected_foods
         from list 
    

    DEMO

    【讨论】:

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