Postgresql

將多對多連接的右側轉換為對像數組

  • January 27, 2022

我有 2 張桌子:

subjectsid, class_id, title, created_at, updated_at

marksid, student_id, class_id, mark, created_at, updated_at, subject_id

我想查詢主題表並讓它返回其所有列並標記列,該列是數組類型(並且其中的值應該是對象),基本上具有查詢結果

select * from marks where marks.subject_id = subjects.id;

所以結果行看起來像這樣:

(5,3,"Subject 1","2022-01-25T12:05:11.000Z","2022-01-25T12:05:11.000Z"
, [{id:15, student_id:12, class_id:3, mark:5, created_at:"2022-01-23T12:05:11.000Z", updated_at:"2022-01-23T12:05:11.000Z", subject_id:5}
, {id:23, student_id:12, class_id:3, mark:5, created_at:"2022-01-21T12:05:11.000Z", updated_at:"2022-01-21T12:05:11.000Z", subject_id:5}
 ])

問題類似於將多對多連接的右側轉換為數組

最好的解決方案取決於缺少的細節。簡單的相關子查詢是各種選項之一(特別適用於小選擇)。

用於將json_agg()行聚合到對像數組中:

SELECT *, (SELECT json_agg(m.*) FROM marks m WHERE m.subject_id = s.id) AS marks
FROM   subjects s;

要僅使用列的子集,請參閱:

引用自:https://dba.stackexchange.com/questions/306694