如何选择与表A的条目相关的表B的多个条目

时间:2019-06-14 09:54:25

标签: mysql

我有一个表“电影”和一个表“导演”。这些通过表“ MovieDirector”以多对多关系连接。这些表具有以下字段:

Movie:
uid
name
release_date

Director:
uid
name

MovieDierector:
uid
movie_id
director_id

我现在要列出所有电影及其导演。可能有不止一位导演在拍电影。如果是这种情况,我希望结果看起来像这样:

movie   | release-date | director
movie A | 2011         | director 1, director 2
movie B | 2013         | director 1
movie C | 1999         | director 3

我尝试了所有可能组合的内部联接,左联接,右联接。但我总是得到以下结果:

movie   | release-date | director
movie A | 2011         | director 1
movie A | 2011         | director 2
movie B | 2013         | director 1
movie C | 1999         | director 3

所有不同的联接组合都会改变条目的顺序。

有人可以告诉我,如果使用MySQL甚至可以实现?如果是,该怎么做?如果不是这样,用多个SQL请求实现此目标的最佳方法是什么?

2 个答案:

答案 0 :(得分:1)

您可以通过将GROUP BY与聚合函数GROUP_CONCAT()结合使用来完成此操作

SELECT Movie.uid, 
       Movie.name, 
       Movie.release_date, 
       GROUP_CONCAT(Director.name) AS directors 
FROM Movie 
INNER JOIN MovieDierector on Movie.uid = MovieDierector.movie_id 
INNER JOIN Director ON Director.uid = MovieDierector.director_id 
GROUP BY Movie.uid

答案 1 :(得分:1)

SELECT `Movie`.`name`                                  AS `movie`,
       `release_date`                                  AS `release-date`,
        GROUP_CONCAT(`Director`.`name` SEPARATOR ', ') AS `director`
FROM `MovieDierector`
JOIN `Movie` ON `MovieDierector`.`movie_id` = `Movie`.`uid`
JOIN `Director` ON `MovieDierector`.`director_id` = `Director`.`uid`
GROUP BY `Movie`.`uid`

您可以测试here