Вярвам, че това е, което търсите или може да ви накара да започнете:
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
За therapists.id = 1
това трябва да ви даде резултати:
+----------------+-----------+-----------------------+
| therapist_name | day | locations |
+----------------+-----------+-----------------------+
| Therapist 1 | monday | Location 1,Location 2 |
| Therapist 1 | wednesday | Location 3 |
| Therapist 1 | friday | Location 1 |
+----------------+-----------+-----------------------+
Ако трябва да свържете day
с locations
колона след това използвайте прост 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
Изходът трябва да изглежда така:
+----------------+-------------------------------+
| therapist_name | locations |
+----------------+-------------------------------+
| Therapist 1 | monday(Location 1,Location 2) |
| Therapist 1 | wednesday(Location 3) |
| Therapist 1 | friday(Location 1) |
+----------------+-------------------------------+
Ако трябва да групирате всичко в един ред за всеки терапевт, тогава можете да GROUP_CONCAT()
отново.
Редактиране след коментари :
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
Не съм тествал кода, така че може да има някои дребни грешки за настройване. Няма начин да го тествате.