MySQL使用中间表查询具有多种类型的电影

时间:2016-04-18 09:30:13

标签: mysql sql

我几乎不使用MySQL所以我对此很新。我的最终目标是拥有一个可以放入Java的列表,其中包含电影ID,电影名称和类型列表。我只想弄清楚一个SQL查询(所以我以后可以解析其他的东西)。我有三张桌子:

CREATE TABLE `movies` (
  `id` int NOT NULL AUTO_INCREMENT,
  `title` varchar(100) NOT NULL DEFAULT '',
  `year` int NOT NULL,
  PRIMARY KEY(`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `genres` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(32) NOT NULL DEFAULT '',
  PRIMARY KEY(`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `genres_in_movies` (
  `genre_id` int NOT NULL,
  `movie_id` int NOT NULL,
  FOREIGN KEY (`genre_id`) REFERENCES `genres`(`id`),
  FOREIGN KEY (`movie_id`) REFERENCES `movies`(`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

假设我的表格具有以下值:

MOVIES
------
1  Zoolander      2001
2  Citizen Kane   1941
3  Psycho         1960

GENRES
------
1  Comedy
2  Horror
3  Drama
4  Suspense
5  Romance
6  Documentary

GENRES_IN_MOVIES (genre_id, movie_id)
------
1  1  -- Comedy   - Zoolander
3  2  -- Drama    - Citizen Kane
4  2  -- Suspense - Citizen Kane
2  3  -- Horror   - Psycho
5  3  -- Romance  - Psycho
4  3  -- Suspense - Psycho

我希望以下输出包含我的查询:

MOVIE LIST
------
1  Zoolander     2001  Comedy
2  Citizen Kane  1949  Drama, Suspense
3  Psycho        1960  Horror, Romance, Suspense

我尝试了这个查询:

SELECT movies.*, genres.name
FROM movies 
INNER JOIN genres_in_movies ON genres_in_movies.movie_id = movies.id
INNER JOIN genres ON genres_in_movies.genre_id = genres.id
GROUP BY movies.title;

但它只会给我一个类型名称。所以它看起来像这样:

MOVIE LIST
------
1  Zoolander     2001  Comedy
2  Citizen Kane  1949  Drama
3  Psycho        1960  Horror

如何检索所有类型?

1 个答案:

答案 0 :(得分:3)

您可以使用group_concat将多个值放在一起

SELECT m.id, m.title, m.year,
       group_concat(g.name) as genres
FROM movies m
INNER JOIN genres_in_movies ON gm.movie_id = m.id
INNER JOIN genres ON gm.genre_id = g.id
GROUP BY m.id, m.title, m.year