You're in luck. MySQL offers a handy function called GROUP_CONCAT()
which you can use to build that result set:
SELECT o.id_org, o.org_name, GROUP_CONCAT(s.staff_name_id SEPARATOR ' ')
FROM organisations o
JOIN (
SELECT id_staff,
id_org,
CONCAT(id_staff, ' ', staff_name) staff_name_id
FROM staff
) s ON (s.id_org = o.id_org)
GROUP BY o.id_org, o.org_name;
Test case:
CREATE TABLE organisations (id_org int, org_name varchar(20));
CREATE TABLE staff (id_staff int, staff_name varchar(20), id_org int);
INSERT INTO organisations VALUES (1, 'Organiz1');
INSERT INTO organisations VALUES (2, 'Organiz2');
INSERT INTO staff VALUES (1, 'John', 1);
INSERT INTO staff VALUES (2, 'Jack', 1);
INSERT INTO staff VALUES (3, 'Sally', 1);
INSERT INTO staff VALUES (4, 'Peter', 1);
INSERT INTO staff VALUES (5, 'Andy', 2);
INSERT INTO staff VALUES (6, 'Joe', 2);
Result:
+--------+----------+---------------------------------------------+
| id_org | org_name | GROUP_CONCAT(s.staff_name_id SEPARATOR ' ') |
+--------+----------+---------------------------------------------+
| 1 | Organiz1 | 1 John 2 Jack 3 Sally 4 Peter |
| 2 | Organiz2 | 5 Andy 6 Joe |
+--------+----------+---------------------------------------------+
2 rows in set (0.00 sec)
UPDATE:
@Micahel's solution also returns the same result. I recommend using that solution since you can concatenate your fields directly in the GROUP_CONCAT()
function, instead of using a derived table:
SELECT o.id_org,
o.org_name,
GROUP_CONCAT(CONCAT(id_staff, ' ', staff_name) SEPARATOR ' ')
FROM organisations o
JOIN staff s ON (s.id_org = o.id_org)
GROUP BY o.id_org, o.org_name;