I am trying to write an SQL query to pull data from two tables, and would like to combine several results in a single row, as in:
+---------------------+----------------------------------+
| name | numbers |
+---------------------+----------------------------------+
| Bob Doe | N/A |
| Mary Jones | +8 213 621 0002,+6 800 444 4444 |
| Anna Smith | +4 71 793 336 |
| Sami Doe | +555 50 333 3333 |
| John Smith | +3 604 222 4444,+44 20 8759 9036 |
+---------------------+----------------------------------+
As you can see, Mary Jones has two numbers, etc. This is the query I have:
SELECT CONCAT_WS(' ', people.first_name, people.last_name) AS name,
COALESCE(phones.number, 'N/A') AS numbers
FROM people
LEFT JOIN phones
ON phones.user_id = people.id;
I've been trying to use GROUP BY
, but I'm not sure how to incorporate it into my query.
The schema looks something like this:
mysql> select * from people;
+----+------------+-------------+
| id | first_name | last_name |
+----+------------+-------------+
| 1 | John | Smith |
| 2 | Mary | Jones |
| 3 | Bob | Doe |
| 4 | Sami | Doe |
| 5 | Anna | Smith |
+----+------------+-------------+
mysql> select * from phones;
+----+---------+------------------+
| id | user_id | number |
+----+---------+------------------+
| 1 | 2 | +1 213 621 0002 |
| 2 | 2 | +1 800 444 4444 |
| 3 | 1 | +1 604 444 4444 |
| 4 | 1 | +44 20 8759 9036 |
| 5 | 4 | +358 50 333 3333 |
+----+---------+------------------+