小编cho*_*sli的帖子

从Postgres中的2个聚合列构建JSON

使用Postgres-Db作为json文档的源代码,我需要将两列从表转换为JSON对象.

所以我在颜色表中有"color_id","language"和"name"列:

    color_id |   language  | name
    1        |      "de"   |  "blau"
    1        |      "en"   |  "blue"
    1        |      "fr"   |  "bleu"

我想生成一个JSON对象,如:

    {
      "de": "blau",
      "fr": "bleu",
      "en": "blue"
    }

我开始了

    SELECT
      array_to_json(array_agg((language::text, name::text))),
      color_id
    FROM colors
    GROUP BY color_id;

不幸的是产生了

    array to json                 | color_id
    "[{"f1":"de","f2":"blau"}     |
      , {"f1":"en","f2":"blue"}   | 1
      , {"f1":"fr","f2":"bleu"}]" | 

我认为这很简单 - 或多或少 - 但发现自己处于误导性结果和语法错误的死胡同.

亲切的问候,多米尼克

postgresql json aggregate aggregate-functions jsonb

7
推荐指数
1
解决办法
2180
查看次数

标签 统计

aggregate ×1

aggregate-functions ×1

json ×1

jsonb ×1

postgresql ×1