PostgreSQL group_concat 行为 json

PostgreSQL group_concat rows as json

我在 mysql 中有一个查询,想在 PostgreSql 中进行同样的查询。

查询如下:

-- mysql
SELECT cat.id, cat.category,
CONCAT('[',
      GROUP_CONCAT(CONCAT('{"rate":"',mod.rate,'", "model_name":"', mod.modelName, '", "capacity":"',mod.capacity,'"}')), ']') vehicles 
      FROM categories cat 
      LEFT JOIN models mod 
      ON cat.id = mod.category_id 
      GROUP BY cat.id

这将得到如下输出:

id  |  category  |  vehicles
__________________________________________________________________________
1   |  2-wheeler |  [ { "rate": "400", "model_name": "Pulsar 12", ... }, {...} ]
2   |  4-wheeler |  [ { "rate": "800", "model_name": "Honda 12", ... }, {...} ]

我正在尝试与 PostgreSql 相同。

这是我卡住的地方:

-- postgres
SELECT cat.id, cat.category,
CONCAT('[',
      array_to_string(CONCAT('{"rate":"',mod.rate,'", "model_name":"', mod.modelName, '", "capacity":"',mod.capacity,'"}')), ']') vehicles 
      FROM categories cat 
      LEFT JOIN models mod 
      ON cat.id = mod.category_id 
      GROUP BY cat.id

我不知道如何推进这个。

此外,表格:

型号:

id  |  modelName   |  rate  |  category_id
_____________________________________________
1   |  Pulsar - 12 |  400   |  1
2   |  Honda       |  800   |  2

类别:

id  | category
__________________
1   | 2-wheeler
2   | 4-wheeler

您将不得不使用 JSON_BUILD_OBJECT 构建单个 JSON 对象,然后 JSON_AGG 构建这些对象的数组:

SELECT cat.id, cat.category,
(SELECT json_agg(
  json_build_object(
    'rate',mod.rate,
    'model_name', mod.modelName, 
    'capacity',mod.capacity
  )) AS vehicles 
  FROM models AS mod WHERE category_id = cat.id
) AS models
FROM categories AS cat 

您可以使用内置的 PostgreSQL 函数来构建 JSON 对象。

select cat.id, cat.category, json_agg(row_to_json(row(mod.rate, mod.modelName))) vehicles from categories cat
left join models mod on cat.id = mod.category_id
group by cat.id, cat.category;

结果会是

    id  category    vehicles
1   1   2-wheeler   [{"f1":400,"f2":"Pulsar - 12"}]
2   2   4-wheeler   [{"f1":800,"f2":"Honda"}]