嵌套的GROUP_CONCAT MySQL?

时间:2016-10-20 06:13:39

标签: mysql

Database Layout

好的,我说我的数据库布局类似于我提供的示例中的数据库布局。在上面的例子中,电影有语言版本,而movie_releases也有不同影院的影院版本。

现在,如果我想查询数据库以获取所有电影的剧场版本以及所有的电影放映,我该怎么做?

我目前的代码是:

select
      GROUP_CONCAT(movie.name, ",", language.lang, ",", GROUP_CONCAT(theatre.name)) as releases
from
    movie
        left join movie_releases on movie_releases.movie_id = movie.id
        left join language on movie_release.language_id = language.id
        left join theatre_release on theatre_release.movie_release_id = movie_release.id
        left join theatre on theatre.id = theatre_release.theatre_id

显然这不起作用,因为你不能像这样嵌套GROUP_CONCAT函数。

我想要的输出就像是

["Spiderman", "English", ["Cinema Theatre", "Garden Cinemas"]]
["Spiderman", "Spanish", ["El Cine Grande"]]
["Batman", "English", ["Town Movies"]]

1 个答案:

答案 0 :(得分:1)

SELECT
    CONCAT(
        '["', `movie`.`name`, '"',
        ', ',
        '"', releases.lang, '"',
        ', [',
        releases.theatres,
        ']]'
    ) AS `release`
FROM
    movie
LEFT JOIN (
    SELECT
        movie_id,
        `language`.lang,
        GROUP_CONCAT('"', theatre.`name`, '"') AS theatres
    FROM
        movie_release
    LEFT JOIN theatre_release ON theatre_release.movie_release_id = movie_release.id
    LEFT JOIN theatre ON theatre.id = theatre_release.theatre_id
    LEFT JOIN `language` ON `language`.id = movie_release.language_id
    GROUP BY
        movie_id,
        language_id
) AS releases ON releases.movie_id = movie.id

您可以将剧院分组,然后根据他们与发行版的关系将它们加入到电影中。

通过以您的格式提供数据,可能会使查询更难以阅读。所以这里是没有花哨格式的查询。

SELECT
    CONCAT(
        `movie`.`name`,
        ' ',
        releases.lang,
        ' ',
        releases.theatres
    ) AS `release`
FROM
    movie
LEFT JOIN (
    SELECT
        movie_id,
        `language`.lang,
        GROUP_CONCAT(theatre.`name`) AS theatres
    FROM
        movie_release
    LEFT JOIN theatre_release ON theatre_release.movie_release_id = movie_release.id
    LEFT JOIN theatre ON theatre.id = theatre_release.theatre_id
    LEFT JOIN `language` ON `language`.id = movie_release.language_id
    GROUP BY
        movie_id,
        language_id
) AS releases ON releases.movie_id = movie.id

要添加分隔符,您只需调整CONCATGROUP_CONCAT