I'm trying select the results of a one-to-many relation and get the results in multiple columns. My tables look like:
Table users:
+----+----------+
| id | user |
+----+----------+
| 1 | jenny |
| 2 | chris |
| 3 | harry |
+----+----------+
Table locations:
+----+-------------+
| id | location |
+----+-------------+
| 1 | New York |
| 2 | Washington |
| 3 | Memphis |
| 4 | Dallas |
| 5 | Las Vegas |
+----+-------------+
Table user_locations:
+----+---------+-------------+
| id | user_id | location_id |
+----+---------+-------------+
| 1 | 1 | 1 |
| 2 | 1 | 3 |
| 3 | 1 | 5 |
| 4 | 2 | 2 |
| 5 | 2 | 4 |
| 6 | 3 | 4 |
| 7 | 3 | 5 |
| 8 | 3 | 2 |
+----+---------+-------------+
The result I'm trying to get is:
+---------+-------+------------+------------+------------+
| user_id | user | location_1 | location_2 | location_3 |
+---------+-------+------------+------------+------------+
| 1 | jenny | New York | Memphis | Las Vegas |
| 2 | chris | Washington | Dallas | NULL |
| 3 | harry | Dallas | Las Vegas | Washington |
+---------+-------+------------+------------+------------+
I tried several queries with left join and group by but I seem to be getting the first location only.
Thanks in advance.