问题
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
回答1:
Second Update
I don't like this it feels too much like "brute force", and I guess there is a more elegant way ...
select concat('{ "users": [', group_concat(json.hobbies), '] }') as hobbies
from
(
select concat('{"firstname": "',u.firstname,'", "hobbies": [', group_concat(json_object('id',h.id,'name',h.hobby),''), ']}') hobbies
from users u
left join hobbies h on u.id = h.user
group by u.id
order by u.firstname
) as json
Output
{ "users": [{"firstname": "Felix", "hobbies": [{"id": 1, "name": "cooking"},{"id": 2, "name": "cat"}]},{"firstname": "Michael", "hobbies": [{"id": 3, "name": "piano"}]},{"firstname": "Tobias", "hobbies": [{"id": null, "name": null}]}] }
First Update
I've lost my battle with MySQL JSON (for now). The closest I could get was the following, which I guess might still be of some use:
select u.firstname, group_concat(json_object('id',h.id,'name',h.hobby),'') hobbies
from users u
left join hobbies h on u.id = h.user
group by u.id
order by u.firstname
Output
+-----------+-------------------------------------------------------+
| firstname | hobbies |
+-----------+-------------------------------------------------------+
| Felix | {"id": 1, "name": "cooking"},{"id": 2, "name": "cat"} |
| Michael | {"id": 3, "name": "piano"} |
| Tobias | {"id": null, "name": null} |
+-----------+-------------------------------------------------------+
Original Answer
Not sure about JSON, will this suffice for the SQL side?
select
u.id,
u.firstname,
group_concat(h.hobby ORDER BY h.ID SEPARATOR ',') as hobbies
from
my_users u
LEFT JOIN hobbies h ON
u.ID = h.user
group by
u.id,
u.firstname
Output
+----+-----------+-------------+
| id | firstname | hobbies |
+----+-----------+-------------+
| 1 | Felix | cooking,cat |
| 2 | Michael | piano |
| 3 | Tobias | NULL |
+----+-----------+-------------+
来源:https://stackoverflow.com/questions/43868757/sql-to-retrieve-multidimensional-array