从两个MySQL表中选择时出错

时间:2016-12-10 09:27:40

标签: mysql

我有3个表:movieactormovie_actor_mapping。我写了一个查询,从每个电影的表电影和组演员中选择数据。但之后我又添加了两个表movie_player_episode_mappingplayer,我必须修改我的查询以选择和分组可用于电影的季节。例如,如果表movie_player_episode_mapping包含movie_id = 1的第1季和第2季,则必须获取字符串1,2

所以,我的表:

CREATE TABLE `movie` (
  `movie_id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(50) DEFAULT NULL,
  `rating` float(2,1) DEFAULT NULL,
  PRIMARY KEY (`movie_id`),
  UNIQUE KEY `title` (`title`)
) 

CREATE TABLE `actor` (
  `actor_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` varchar(40) DEFAULT NULL,
  PRIMARY KEY (`actor_id`),
  UNIQUE KEY `name` (`name`)
)

CREATE TABLE `movie_actor_mapping` (
  `movie_actor_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `movie_id` int(10) UNSIGNED DEFAULT NULL,
  `actor_id` int(10) UNSIGNED DEFAULT NULL,
  PRIMARY KEY (`movie_actor_id`),
  UNIQUE KEY `movie_actor_id` (`movie_actor_id`)
) 

我的疑问:

SELECT title, group_concat(a.name separator ', ') as actors
FROM movie m
INNER JOIN movie_actor_mapping ma ON m.movie_id = ma.movie_id
INNER JOIN actor a ON a.actor_id = ma.actor_id
WHERE m.rating IS NOT NULL
GROUP BY m. movie_id
ORDER BY m.rating DESC;

另外我的两张桌子:

CREATE TABLE `movie_player_episode_mapping` (
  `movie_id` int(11) UNSIGNED,
  `season` tinyint(11) UNSIGNED,
  `episode` tinyint(11) UNSIGNED,
  `player_id` tinyint(11) UNSIGNED,
  `path` TEXT
);

CREATE TABLE `player` (
  `player_id` int(11) UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `hostname` VARCHAR(30),
  `name` VARCHAR(30),
  UNIQUE KEY `name` (`name`)
);

我试图像这样修改我的查询:

SELECT title, group_concat(a.name separator ', ') as actors, group_concat(mpe.season separator ', ') as seasons
    FROM movie m, movie_player_episode_mapping mpe
    INNER JOIN movie_actor_mapping ma ON m.movie_id = ma.movie_id
    INNER JOIN actor a ON a.actor_id = ma.actor_id
    WHERE m.rating IS NOT NULL
    GROUP BY m. movie_id
    ORDER BY m.rating DESC;

但我收到了错误:[42S22][1054] Unknown column 'm.movie_id' in 'on clause'

我也尝试过下一个查询,但结果错了。例如,如果我的movie_player_episode_mapping仅包含movie_id=1一个季节的行,我就会seasons: "1, 1, 1, 1, 1, 1, 1, 1, 1"代替seasons: "1"

SELECT title, group_concat(a.name separator ', ') as actors, group_concat(mpe.season separator ', ') as seasons
FROM movie m
INNER JOIN movie_player_episode_mapping mpe ON m.movie_id = mpe.movie_id
INNER JOIN movie_actor_mapping ma ON m.movie_id = ma.movie_id
INNER JOIN actor a ON a.actor_id = ma.actor_id
WHERE m.rating IS NOT NULL
GROUP BY m. movie_id
ORDER BY m.rating DESC;

我的错误在哪里?我该如何解决?

1 个答案:

答案 0 :(得分:0)

SELECT title, group_concat(a.name separator ', ') as actors, group_concat(mpe.season separator ', ') as seasons
FROM movie m
INNER JOIN movie_actor_mapping ma ON m.movie_id = ma.movie_id
INNER JOIN actor a ON a.actor_id = ma.actor_id, movie_player_episode_mapping, mpe
WHERE m.rating IS NOT NULL
GROUP BY m. movie_id
ORDER BY m.rating DESC;

可能这可以帮助你......你的上一次查询