Does anyone know if it is possible to write a query that can produce the following output based on the below tables?
I have managed to create the below results by creating three separate queries and passing the previous queries’ result set into the next query. But I was hoping for a more efficient way.
I want this output using ONE SQL if possible?
baseball computer laptop
Jane Doe 5
Joe Blogs 8 8
These are the tables I have to work with:
persons table
id first_name last_name
101 Jane Doe
576 Joe Blogs
hobbies table
id hobby_type hours_spent
1 sports 5
2 technology 8
hobby_types table
id name
33 computer
39 baseball
45 laptop
persons_hobbies join-table for person and hobbies
id person_id hobby_id
1 101 1
3 576 1
2 576 2
hobbies_hobby_types join-table for hobbies and hobby_types
hobby_id hobby_type_id
1 39
2 33
3 45
You are trying to get a so-called pivot table.
I’m afraid there is no way to do it in MySQL with an unlimited number of columns, but maybe I’m wrong. Use your newly learned keyword to find a lot of information on this topic.