I have an app with users; the users can create bookmarks, and each bookmark can have multiple tags.
So, if I'm not mistaken in the notation: user =* bookmark *=* tag
Now I try to retrieve all users with a JSON array with the tags they used. I need a JSON array because I may need to retrieve the name or other data from the tags or the bookmarks:
SELECT
`user`.id,
JSON_ARRAYAGG(
JSON_OBJECT(
"id", tag.id
)
) AS tags,
JSON_ARRAYAGG(
JSON_OBJECT(
"id", bookmark.id
)
) AS bookmarks
FROM tag
INNER JOIN bookmark_tag ON bookmark_tag.tag_id = tag.id
INNER JOIN bookmark ON bookmark.id = bookmark_tag.bookmark_id
INNER JOIN `user` ON user.id = bookmark.user_id
GROUP BY `user`.id;
But this returns duplicated ids both for bookmarks and tags:
Here is a DB fiddle to play with: https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=56ac0313fe2a3bf7af32a3ed9a3ea78a
How can I do that?