Предполагая, что вы хотите вывод JSON (B), вы можете сделать это с row_to_jsonb()
и jsonb_agg()
:
select
q.*,
(select jsonb_agg(row_to_json(a)) from answers a where a.question_id = q.id) answers
from questions q
Демонстрация на DB Fiddle :
id | type | test_id | text | answers
-: | :------- | ------: | :------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1 | single | 1 | What you can do? | [{"id": "1", "answer": "Everything", "question_id": 1, "is_right_answer": true}, {"id": "2", "answer": "Nothing", "question_id": 1, "is_right_answer": false}, {"id": "3", "answer": "That depends", "question_id": 1, "is_right_answer": false}]
2 | multiple | 2 | What he can do? | [{"id": "4", "answer": "Everything", "question_id": 2, "is_right_answer": false}, {"id": "5", "answer": "Nothing", "question_id": 2, "is_right_answer": true}, {"id": "6", "answer": "That depends", "question_id": 2, "is_right_answer": true}]
3 | anything | 3 | What I can do? | [{"id": "7", "answer": "Everything", "question_id": 3, "is_right_answer": true}, {"id": "8", "answer": "Nothing", "question_id": 3, "is_right_answer": true}, {"id": "9", "answer": "That depends", "question_id": 3, "is_right_answer": true}]
5 | multiple | 1 | Are you a man? | <em>null</em>
6 | anything | 1 | What are you going to do today? | <em>null</em>
8 | anything | 3 | 5 | <em>null</em>