Then better understand the problem here are my thoughts and possible solutions.
Solution 1:
The best idea would be to restructure the tables with Foreign Keys. N-1 if areas can only have one administrator. N-N if an area can have multiple administrators and each administrator can manage multiple areas.
If option N-1 is chosen, the @Ricardo-punctual response is exactly what you need. Since the table regions
have a foreign key for the table administrators
.
Ad-hoc response for reference:
SELECT
a.nomeAdm as nome,
GROUP_CONCAT(DISTINCT r.nomeREg SEPARATOR ", ") as regiao
FROM regiao r
INNER JOIN administrador a ON r.idAdm = a.idAdm
GROUP BY r.idAdm;
If N-N is the need, I keep the previous answer which is to have a pivot table with foreign keys for regions
and administrators
.
SELECT
a.nome as administrador,
GROUP_CONCAT(DISTINCT r.nome SEPARATOR ", ") as regioes
FROM administradores as a
INNER JOIN adm_regioes AS ar ON ar.adm_id = a.id
INNER JOIN regioes AS r ON ar.regiao_id = r.id
GROUP BY a.id;
Solution 2:
If it is not possible to restructure the tables, it is possible to make a Join using REGEXP so that the DBMS recognizes the field regions
and can reference the table regions
.
An example would be:
SELECT
a.nome as nome,
a.regions as regions,
GROUP_CONCAT(DISTINCT r.nome SEPARATOR ', ') as regions_concat
FROM administrators as a
INNER JOIN regions as r
ON a.regions REGEXP CONCAT("[[:<:]]", r.id, "[[:>:]]")
GROUP BY a.id;
Upshot:
+-------+---------+----------------------+
| nome | regions | regions_concat |
+-------+---------+----------------------+
| Pedro | 1 | Sao paulo |
| João | 2,3 | Campinas, Manaus |
| José | 4,5 | Campo Grande, Santos |
+-------+---------+----------------------+
The INNER JOIN
would be done by applying the REGEXP in the column where the symbols [[:<:]]
and [[:>:]]
are the word boundaries (equivalent to \b
in other REGEXP engines).
In this way your problem is solved, but it should be pointed out that it is not ideal and also not at all performatic.
See working on Dbfiddle
PS: You need to test if it works normally with two or more digit numbers as well.
These are the options I see without having to deal with at the application level. I hope it helps.
I think if you run in the same select, it will duplicate the name of the administrator...
– Ricardo Pontual
I’ll update with DISTINCT then.
– fernandosavio
It’s not an N-N, I only have two tables, the Administrator and the Region table....
– Daywison Ferreira Leal
Sorry @Daywisonferreiraleal... better answer.
– fernandosavio