在一行中获取一对多关系中的所有值

时间:2013-02-25 13:12:21

标签: mysql left-join concatenation one-to-many

我的数据库中有一对多的关系。 enter image description here

我想将所有连接在一行的影院的所有城市都取为CSV。我试过了:

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

但这只会让第一部电影回归。

3 个答案:

答案 0 :(得分:15)

使用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

答案 1 :(得分: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;

答案 2 :(得分: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