【发布时间】:2016-04-18 17:46:47
【问题描述】:
我几乎不使用 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
如何检索所有类型?
【问题讨论】:
-
你考虑过group_concat吗?
-
@jarlh 我会查一下,老实说,我对 SQL 还是很陌生
-
一般 GROUP BY 规则说:“如果指定了 GROUP BY 子句,则 SELECT 列表中的每个列引用必须标识一个分组列或作为集合函数的参数。” (然而,旧的 MySQL 版本不在乎,但新的呢!)