开发者

Mysql three table join while concatenating a column?

开发者 https://www.devze.com 2023-03-24 02:50 出处:网络
I have the following tables: Table categories { -id--name- 1Action 2Comedy 4Drama 5Dance } Table movies { -id--name--description-

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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号