1

I have a query in mysql and want to do the same in PostgreSql.

Here's the query:

-- 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

This will get the output as:

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

I am trying to get the same with PostgreSql.

here's where I am stuck:

-- 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

I don't know how to move forward with this.

Also, the tables:

models:

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

categores:

id  | category
__________________
1   | 2-wheeler
2   | 4-wheeler
Azima
  • 3,835
  • 15
  • 49
  • 95

2 Answers2

3

You will have to use JSON_BUILD_OBJECT to build the individual JSON objects and then JSON_AGG to build an array of those objects:

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 
IVO GELOV
  • 13,496
  • 1
  • 17
  • 26
1

You can use built-in PostgreSQL's functions to build JSON objects.

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;

The result will be

    id  category    vehicles
1   1   2-wheeler   [{"f1":400,"f2":"Pulsar - 12"}]
2   2   4-wheeler   [{"f1":800,"f2":"Honda"}]
Vadim Kharitonov
  • 970
  • 6
  • 14