我有两个桌子。 旅行者和城市
城市表:
City_id City_name
1 Delhi
2 Mumbai
3 Newyork
4 Sydney
用户表:
traveller_name traveled_city
harry 1,2
peter 2,3,4
john 2,4
如何获取旅行者这样旅行的城市?
traveller_name travelled_city
harry Delhi , Mumbai
答案 0 :(得分:2)
您的数据库架构未规范化。 first normal form告知您需要在该字段中具有原子值。同样考虑其他普通形式,您需要有单独的User
表和UserCity
表。
如果对表进行规范化,则查询将变得更加简单。
用户表
--------+----------
| UserId UserName |
--------+----------
| 1 | Harry |
| 2 | Peter |
-------------------
UserCity表(它是网桥表)
--------+----------
| UserId CityId |
--------+----------
| 1 | 1 |
| 1 | 2 |
-------------------
现在,您可以轻松查询
SELECT u.UserName as traveller_name, group_concat(c.cityname,',') as travelled_city
FROM User as u
JOIN UserCity as uc
ON u.UserId = uc.UserId
JOIN City as c
ON uc.CityId = c.CityId
GROUP BY u.UserName
答案 1 :(得分:-1)
选择traveller.traveller_name,GROUP_CONCAT(city.City_name) 来自旅行者 INNER JOIN city ON city.City_id = traveller.traveled_city GROUP BY traveller.traveller_name