Jag tror att det här är vad du letar efter, eller kan få dig igång:
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
För therapists.id = 1
detta borde ge dig resultat:
+----------------+-----------+-----------------------+
| therapist_name | day | locations |
+----------------+-----------+-----------------------+
| Therapist 1 | monday | Location 1,Location 2 |
| Therapist 1 | wednesday | Location 3 |
| Therapist 1 | friday | Location 1 |
+----------------+-----------+-----------------------+
Om du behöver sammanfoga day
med locations
kolumnen använd sedan en enkel 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
Utdata ska se ut så här:
+----------------+-------------------------------+
| therapist_name | locations |
+----------------+-------------------------------+
| Therapist 1 | monday(Location 1,Location 2) |
| Therapist 1 | wednesday(Location 3) |
| Therapist 1 | friday(Location 1) |
+----------------+-------------------------------+
Om du behöver gruppera allt i en rad för varje terapeut kan du GROUP_CONCAT()
igen.
Redigera efter kommentarer :
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
Jag har inte testat koden så det kan finnas några mindre misstag att justera. Inget sätt att testa det atm.