Ik denk dat dit is wat u zoekt, of waarmee u aan de slag kunt:
SELECT
t.therapist_name,
dl.day,
GROUP_CONCAT(DISTINCT dl.name SEPARATOR ',') AS locations
FROM
therapists t
LEFT JOIN days_location dl ON dl.therapist_id = t.id
LEFT JOIN location l ON dl.location_id = l.id
GROUP BY t.therapist_name, dl.day
Voor therapists.id = 1
dit zou je resultaten moeten opleveren:
+----------------+-----------+-----------------------+
| therapist_name | day | locations |
+----------------+-----------+-----------------------+
| Therapist 1 | monday | Location 1,Location 2 |
| Therapist 1 | wednesday | Location 3 |
| Therapist 1 | friday | Location 1 |
+----------------+-----------+-----------------------+
Als u day
moet samenvoegen met locations
kolom gebruik dan een eenvoudige CONCAT()
:
SELECT
therapist_name,
CONCAT(day, '(', locations, ')') AS locations
FROM (
SELECT
t.therapist_name,
dl.day,
GROUP_CONCAT(DISTINCT dl.name SEPARATOR ',') AS locations
FROM
therapists t
LEFT JOIN days_location dl ON dl.therapist_id = t.id
LEFT JOIN location l ON dl.location_id = l.id
GROUP BY t.therapist_name, dl.day
) t
GROUP BY therapist_name, locations
Uitvoer zou er als volgt uit moeten zien:
+----------------+-------------------------------+
| therapist_name | locations |
+----------------+-------------------------------+
| Therapist 1 | monday(Location 1,Location 2) |
| Therapist 1 | wednesday(Location 3) |
| Therapist 1 | friday(Location 1) |
+----------------+-------------------------------+
Als u alles voor elke therapeut in één rij moet groeperen, kunt u GROUP_CONCAT()
nogmaals.
Bewerken na opmerkingen :
SELECT
therapist_name,
GROUP_CONCAT( CONCAT(day, '(', locations, ')') SEPARATOR ',' ) AS locations
FROM (
SELECT
t.therapist_name,
dl.day,
GROUP_CONCAT(DISTINCT dl.name SEPARATOR ',') AS locations
FROM
therapists t
LEFT JOIN days_location dl ON dl.therapist_id = t.id
LEFT JOIN location l ON dl.location_id = l.id
GROUP BY t.therapist_name, dl.day
) t
GROUP BY therapist_name
Ik heb de code niet getest, dus er kunnen enkele kleine fouten zijn om aan te passen. Geen manier om het te testen atm.