I have 3 tables. For the purposes of this example I will simplify it as much as I can.
First table contains movie ids and names, second table contains genre ids and genre names (action, drama, etc). 3rd table stores the genre id associated with each movie, since some movies have more than one. It has 2 columns, genre_id and movie_id. Fairy simple stuff. Im trying to output the list of movies, along with a list of genres associated with each movie.
SELECT * FROM movies LEFT JOIN gen_pairs ON movies.mov_id = gen_pairs.gen_movieid LEFT JOIN categories ON gen_pairs.gen_catid = categories.cat_id GROUP BY mov_id
This will obviously output a single genre of each film, even if it has multiple ones in the gen_pairs table. How would I get it to display a comma separated list of genres for each movie, without running a sub-query for each item?
Your select should build the Cartesian product, so you’ll get output like
But it sounds like you want this instead:
MySQL has a GROUP_CONCAT function to do what you want:
Note the GROUP_CONCAT and GROUP BY.