Concatenando resultados em uma coluna no MySql com o GROUP_CONCAT
Olá!
Certo dia precisei listar códigos "filhos" agrupados em referencia ao "pai", mas não de forma em linhas, mas sim os códigos "filhos" agrupados colunar. Tipo de tabela N-N.
Entendam no exemplo:
mysql> SELECT DISTINCT
-> parent_id, child_id
-> FROM group_c
-> ORDER BY parent_id;
+-----------+----------+
| parent_id | child_id |
+-----------+----------+
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
| 1 | 4 |
| 2 | 1 |
| 2 | 3 |
| 2 | 4 |
| 2 | 6 |
| 3 | 1 |
| 3 | 2 |
| 4 | 1 |
| 5 | 0 |
+-----------+----------+
12 rows in set (0.00 sec)
Para isso utilizei o seguinte query string sql:
mysql> SELECT DISTINCT
-> parent_id, GROUP_CONCAT(DISTINCT child_id ORDER BY child_id) AS child_id_list
-> FROM group_c
-> group by parent_id
-> ORDER BY parent_id;
+-----------+---------------+
| parent_id | child_id_list |
+-----------+---------------+
| 1 | 1,2,3,4 |
| 2 | 1,3,4,6 |
| 3 | 1,2 |
| 4 | 1 |
| 5 | 0 |
+-----------+---------------+
5 rows in set (0.00 sec)
Por padrão, serão agrupados os child_id_list por vírgula. Mas podemos manipular o separador dessa forma:
mysql> SELECT DISTINCT
-> parent_id, GROUP_CONCAT(DISTINCT child_id ORDER BY child_id SEPARATOR '|') AS child_id_list
-> FROM group_c
-> group by parent_id
-> ORDER BY parent_id;
+-----------+---------------+
| parent_id | child_id_list |
+-----------+---------------+
| 1 | 1,2,3,4 |
| 2 | 1,3,4,6 |
| 3 | 1,2 |
| 4 | 1 |
| 5 | 0 |
+-----------+---------------+
5 rows in set (0.00 sec)
Seja o primeiro a comentar.