我的数据库中有一对多的关系。
我想获取所有城市,所有的电影院都以 CSV 格式附加在一行中。我试过了:
SELECT city.*,CONCAT(cinema_name)
FROM city
LEFT JOIN cinema
ON cinema.city_id=city.city_id
GROUP BY city.city_id
但这只会返回第一个电影院。
我的数据库中有一对多的关系。
我想获取所有城市,所有的电影院都以 CSV 格式附加在一行中。我试过了:
SELECT city.*,CONCAT(cinema_name)
FROM city
LEFT JOIN cinema
ON cinema.city_id=city.city_id
GROUP BY city.city_id
但这只会返回第一个电影院。
使用 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
试试这个查询
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;
对于在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