Mysql three table join while concatenating a column?
I have the following tables:
Table categories {
-id- -name-
1 Action
2 Comedy
4 Drama
5 Dance
}
Table movies {
-id- -name- -description-
1 Example 1 Movie description 1
2 Example 2 Movie description 2
4 Example 3 Movie description 3
}
Table movies_categories {
-movie_id- -category_id-
1 2
2 1
4 3
}
I want to select everything from the movies table, and also get the categories for that movie concatenated in one column separated by a comma (or whatever, separated by something).
I gave it a shot myself but I was not able to concatenate the categories (right now it just selects the first category and ignores the rest), and I was also not able to add a WHERE clause, which i really need. I just got a syntax error, any ideas why?
开发者_JS百科SELECT movies.*, categories.name FROM movies LEFT JOIN movies_categories ON (movies.id = movies_categories.movie_id) LEFT JOIN categories ON (movies_categories.category_id = categories.id)
You can use GROUP_CONCAT:
SELECT movies.*, GROUP_CONCAT(categories.name)
FROM movies
LEFT JOIN movies_categories ON (movies.id = movies_categories.movie_id)
LEFT JOIN categories ON (movies_categories.category_id = categories.id)
GROUP BY movies.id
精彩评论