I'm trying to learn SQL but hitting a wall with the following problem. I can solve it easily using imperative programming but would like to know if it's possible to solve this problem using just a query:
Input
Table 1 (users)
ID | Firstname
--------------
1 | Felix
2 | Michael
3 | Tobias
Table 2 (hobbies)
ID | Hobby | User
------------------------
1 | cooking | 1
2 | cat | 1
3 | piano | 2
Wanted Output
{
"users": [{
"firstname": "Felix",
"hobbies": [{
"id": 1,
"name": "cooking"
}, {
"id": 2,
"name": "cat"
}]
},
{
"firstname": "Michael",
"hobbies": [{
"id": 3,
"name": "piano"
}]
},
{
"firstname": "Tobias",
"hobbies": []
}
]
}
Doesn't need to be directly JSON of course. With joins I've come so far that either a row is created for each hobby x user (two rows for Felix)
Felix | cooking
Felix | cat
Michael | piano
or that some information got lost (Felix' cat got lost)
Felix | cooking
Michael | piano