嗨,嗨,我有一個 Nodejs 服務器,我正在使用 PostgreSQL,這是我資料庫的底部。我如何選擇資料并像這樣表示它(在一個 sql 查詢中):
{lessons: ['lesson1','lesson2'], tests: [{quest:'quest_name',options:['opt1','opt2']}]}
我寫了一個請求,但它遠不是我需要的:
SELECT tests.id,
chapter,
time,
ARRAY_AGG(quests.question) AS questions,
ARRAY_AGG(options.option) AS quest_options
FROM tests
LEFT JOIN quests ON tests.id = quests.test_id
LEFT JOIN options ON quests.id = options.quest_id
WHERE tests.course_id = '${courseId}'
GROUP BY tests.id

uj5u.com熱心網友回復:
您可以使用 acte首先構建問題 JSON 資料,然后將后者與課程聚合:
with tests(q, o) as (
select q.question, json_agg(o.option)
from tests t join quests q on t.id = q.test_id join options o on q.id = o.quest_id
where t.course_id = '${courseId}'
group by q.question
)
select json_build_object('lesson',
(select json_agg(l.lesson_text) from lessons l where l.course_id = '${courseId}'),
'tests',
(select json_agg(json_build_object('quest', t.q, 'options', t.o)) from tests t)
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/362590.html
標籤:sql PostgreSQL的
