I have the following 2 tables: title and photo. I want to return rows from both of these tables that are part of the same group, ordered by timestamp, and grouped into a JSON array.
Example:
groupId | allitems
--------------------------------------------------------------------------------------
1 | [{title1}, {photo1}, {photo2}, {photo3}, {title2}, {photo4}, ...}]
We need the following tables:
title table
titleId | createdDate | groupId | text | ...
---------------------------------------------------------------
1 | 2022-10-01 09:00:00 | 1 | EXAMPLE TITLE 1 | ...
2 | 2022-10-02 08:00:00 | 1 | EXAMPLE TITLE 2 | ...
3 | 2022-10-03 04:00:00 | 2 | EXAMPLE TITLE 3 | ...
photo table
photoId | timestamp | groupId | url | ...
-------------------------------------------------------------
1 | 2022-10-01 10:00:00 | 1 | http://www... | ...
2 | 2022-10-02 03:00:00 | 1 | http://www... | ...
3 | 2022-10-02 11:00:00 | 1 | http://www... | ...
4 | 2022-10-04 01:00:00 | 2 | http://www... | ...
5 | 2022-10-04 05:00:00 | 2 | http://www... | ...
6 | 2022-10-04 06:00:00 | 2 | http://www... | ...
Result
groupId | allitems
----------------------------------------------------------------------------------------------------
1 | [{titleId: 1, createdDate: "2022-10-01 09:00:00", groupId: 1, text: "EXAMPLE TITLE 1", ...},
| {photoId: 1, timestamp: "2022-10-01 10:00:00", groupId: 1, url: "http://www...", ...},
| {photoId: 2, timestamp: "2022-10-02 03:00:00", groupId: 1, url: "http://www...", ...},
| {titleId: 2, createdDate: "2022-10-02 08:00:00", groupId: 1, text: "EXAMPLE TITLE 2", ...}
| {photoId: 3, timestamp: "2022-10-02 08:00:00", groupId: 1, url: "http://www...", ...}]
----------------------------------------------------------------------------------------------------
2 | [{titleId: 3, createdDate: "2022-10-03 04:00:00", groupId: 2, text: "EXAMPLE TITLE 3", ...},
| {photoId: 4, timestamp: "2022-10-04 01:00:00", groupId: 2, url: "http://www...", ...},
| {photoId: 5, timestamp: "2022-10-04 05:00:00", groupId: 2, url: "http://www...", ...},
| {photoId: 6, timestamp: "2022-10-04 06:00:00", groupId: 2, url: "http://www...", ...}]
Each row contains the groupId and all the titles + photos ordered by timestamp, that are in the form of an JSON array.
Any help would be greatly appreciated!