表1:用户
id name
1 name 1
2 name 2
表2:user_city
user_id city_id
1 1
1 2
2 1
2 2
表3:城市
id name_city
1 HCM
2 Ha Noi
3 DA NAng
我的Sql:
select a.*,c.name_city
FROM users as a
INNER JOIN
user_city as b
ON b.user_id = a.id
INNER JOIN city as c
ON c.id = b.city_id
结果:
id name name_city
1 name 1 HCM
2 name 2 Ha Noi
1 name 1 Ha Noi
2 name 2 HCM
我想结果是:
结果:
id name name_city
1 name 1 HCM,Ha Noi
2 name 2 HCM,Ha Noi
答案 0 :(得分:2)
您可以使用GROUP_CONCAT
和GROUP BY
来获得结果
SELECT U.id, U.name, GROUP_CONCAT(c.name_city)
FROM users u
join user_city uc
on u.id = uc.user_id
join city c
on uc.city_id = c.id
group by u.id, u.name