2

I write SQL in postgres 9.3 which works almost perfectly:

SELECT type_id, to_json(array_agg(row(value, id))) AS json FROM sub_types GROUP BY type_id

The result table looks:

type_id | json
1       | [{"f1":"something", "f2":7}, ...]
2       | [{"f1":"something new", "f2":2}, ...]

I am trying to do that the result looks like:

type_id | json
1       | [{"value":"something", "id":7}, ...]
2       | [{"value":"something new", "id":2}, ...]

Basic idea is to to write code (PHP) something close to this: rows = pdo_call_select

rows = pdo_call_select
foreach (rows as row)
{
  print '<span data-id="row->id">'
  foreach (row->json as otherfields)
    print '<input value="otherfields->value" ...'
    ...

and my table is:

id | type_id | value
1      3         something
2      2         blabla
3      3         something new
4      1         ok
...

2 Answers 2

2
create table sub_types (
    id int, type_id int, value text
);
insert into sub_types (id, type_id, value) values
(1, 3, 'something'),
(2, 2, 'blabla'),
(3, 3, 'something new'),
(4, 1, 'ok');

select type_id, json_agg(row_to_json(cj)) as json
from
    sub_types st
    cross join lateral
    (select value, id) cj
group by type_id
;
 type_id |                               json                               
---------+------------------------------------------------------------------
       1 | [{"value":"ok","id":4}]
       3 | [{"value":"something","id":1}, {"value":"something new","id":3}]
       2 | [{"value":"blabla","id":2}]
Sign up to request clarification or add additional context in comments.

Comments

0

I create types for all my json results and cast the rows to the type.

create table sub_types (
    id int, type_id int, value text
);

create type sub_json_type as (value text, id integer);

insert into sub_types (id, type_id, value) values
(1, 3, 'something'),
(2, 2, 'blabla'),
(3, 3, 'something new'),
(4, 1, 'ok');


SELECT type_id, to_json(array_agg(row(value, id)::sub_json_type)) AS json FROM sub_types GROUP BY type_id;

 type_id |                              json                               
---------+-----------------------------------------------------------------
       1 | [{"value":"ok","id":4}]
       2 | [{"value":"blabla","id":2}]
       3 | [{"value":"something","id":1},{"value":"something new","id":3}]
(3 rows)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.