I started working on my first MySQL database and I had a simple problem.
I have films classified by genre in a many-to-many relationship:
'movies' Table
+ --------- + ------------------- +
| movie_id | movie_title |
+ --------- + ------------------- +
| 1 | Indiana Jones |
| 2 | Shaun of the Dead |
+ --------- + ------------------- +
'genres' table
+ --------- + ----------- +
| genre_id | genre_name |
+ --------- + ----------- +
| 1 | adventure |
| 2 | comedy |
| 3 | horror |
+ --------- + ----------- +
'movie_genres' table
+ --------- + --------- +
| movie_id | genre_id |
+ --------- + --------- +
| 1 | 1 |
| 2 | 2 |
| 2 | 3 |
+ --------- + --------- +
What I'm trying to do is search in my table of films by genre and display all genres in which each movie is located, for example:
Searching 'horror'
+ ------------------ + --------------- +
| movie_title | genre_names |
+ ------------------ + --------------- +
| Shaun of the Dead | comedy, horror |
+ ------------------ + --------------- +
Here is a query that I would like to use to search for horror movies
SELECT m.movie_title, GROUP_CONCAT (g.genre_name SEPARATOR ',') as genre_names FROM movies m LEFT JOIN genre_movies gm ON gm.movie_id = m.movie_id LEFT JOIN genres g ON g.genre_id = gm.genre_id GROUP genre_names LIKE '% horror%'
The problem is that this query retrieves the entire set of all tables before filtering it, which I find very inefficient. Is there a better way I could search for one genre by showing all related genres?
source share