2

我的数据库中有一对多的关系。 在此处输入图像描述

我想获取所有城市,所有的电影院都以 CSV 格式附加在一行中。我试过了:

SELECT city.*,CONCAT(cinema_name)
FROM city
LEFT JOIN cinema
ON cinema.city_id=city.city_id
GROUP BY city.city_id

但这只会返回第一个电影院。

4

3 回答 3

16

使用 GROUP_CONCAT 而不是 CONCAT

SELECT
  city.*,
  GROUP_CONCAT(cinema_name) AS `Cinemas`
FROM city
  LEFT JOIN cinema
    ON cinema.city_id = city.city_id
GROUP BY city.city_id
于 2013-02-25T13:13:37.173 回答
1

试试这个查询

SELECT ct.city_id, GROUP_CONCAT(cinema_name) 
FROM cinema c, city ct
WHERE c.city_id = ct.city_id
Group BY c.city_id;
于 2013-02-25T13:14:52.813 回答
1

对于在V5.7上测试的当前版本的 Mysql,如果您希望将该数据作为 json 对象,您可以试试这个。

SELECT
  city.*,
  GROUP_CONCAT(
JSON_OBJECT(
'cinema_name', cinema_name
)) AS `Cinemas`
FROM city
  LEFT JOIN cinema
    ON cinema.city_id = city.city_id
GROUP BY city.city_id
于 2018-06-19T05:36:41.477 回答