sql >> Base de Datos >  >> RDS >> Mysql

MySQL group_concat con seleccionar dentro de seleccionar

Creo que esto es lo que está buscando o podría ayudarlo a comenzar:

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

Para therapists.id = 1 esto debería darte resultados:

+----------------+-----------+-----------------------+
| therapist_name |    day    |       locations       |
+----------------+-----------+-----------------------+
| Therapist 1    | monday    | Location 1,Location 2 |
| Therapist 1    | wednesday | Location 3            |
| Therapist 1    | friday    | Location 1            |
+----------------+-----------+-----------------------+

Si necesita concatenar day con locations columna luego use un simple 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

La salida debería verse así:

+----------------+-------------------------------+
| therapist_name |           locations           |
+----------------+-------------------------------+
| Therapist 1    | monday(Location 1,Location 2) |
| Therapist 1    | wednesday(Location 3)         |
| Therapist 1    | friday(Location 1)            |
+----------------+-------------------------------+

Si necesita agruparlo todo en una fila para cada terapeuta, entonces podría GROUP_CONCAT() de nuevo.

Editar después de los comentarios :

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

No he probado el código, por lo que puede haber algunos errores menores para modificar. No hay forma de probarlo en el cajero automático.