2

I have a database with all movies I've seen in the cinema. it consists of a couple of tables:

  • screenings (main table with, date, cinema, movie, etc.)
  • movies (all information about the movies: title, director, length...)
  • cinemas (information about the cinema I watched it in, not used in my example)
  • tags (tags connected to movies fields: id, tag)
  • tag_scr (link table links tags to screenings, fields: scr_id, tag_id)

Most screenings have one tag connected (can be stuff like, film festival, 3d, premiere, live music) but screenings can also have zero tags or more than one, so what I'm trying to do is to create a query where I list all screenings, and all of the tags connected to that screening concatenated to a string with comas between. My query looks like this now:

SELECT screenings.id, movies.title, tags.tag FROM screenings 
JOIN movies ON screenings.ft = movies.id
LEFT JOIN tag_scr ON screenings.id = tag_scr.scr_id
LEFT JOIN tags ON tag_scr.tag_id = tags.id

And that does what I need except the screenings with multiple tags are listed multiple times in the result. And if I group by screenings.id I only get the first tag on each screening. Is it possible to do what I want, using the concat function, a sub-query or any other method? My database is MySQL 5.5.24.

4

1 に答える 1

0

はい、使用する必要がありますGROUP_CONCAT

SELECT screenings.id, movies.title, GROUP_CONCAT(tags.tag SEPARATOR ',') tags
FROM screenings 
   JOIN movies ON screenings.ft = movies.id
   LEFT JOIN tag_scr ON screenings.id = tag_scr.scr_id
   LEFT JOIN tags ON tag_scr.tag_id = tags.id
GROUP BY screenings.id, movies.title

デフォルトではコンマであるため、SEPARATOR構文は実際には必要ありません。

http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat

幸運を。

于 2013-02-10T22:23:52.060 に答える