gpt4 book ai didi

mysql - 嵌套 GROUP_CONCAT MySQL?

转载 作者:行者123 更新时间:2023-11-28 23:24:09 30 4
gpt4 key购买 nike

Database Layout

好吧,假设我有一个类似于我提供的示例中的数据库布局。在上面的示例中,电影有多种语言版本,而这些 movie_releases 也有不同影院的影院版本。

现在,如果我想查询数据库以获取电影的所有影院发行以及所有 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"]]

最佳答案

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

关于mysql - 嵌套 GROUP_CONCAT MySQL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40146729/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com