I've begun working on my first MySQL database, and I've run into a simple problem.
I have my movies categorized 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 am trying to do is search my movies table by genre, and display all the genres each movie is in, for instance:
Searching 'horror' +------------------+---------------+ |movie_title |genre_names | +------------------+---------------+ |Shaun of the Dead |comedy, horror | +------------------+---------------+
Here is a query I would 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 BY m.movie_id HAVING genre_names LIKE '%horror%'
The problem I have is that this query retrieves the entirety of all the tables before filtering it, which I gather is very inefficient. Is there a better way I could search by one genre while showing all associated genres?