I have a table called USERS which indexes certain nationalities as a comma delimited string.
ID | NOMBRE | NACIONALIDAD
1 | JUAN | 1,2,3
2 | PEDRO | 1,2
3 | JOSE | 1,3
I have my table of NATIONALITIES
ID | NACION
1 | Ruso
2 | Español
3 | Brasileño
How could I make the INNER JOIN so that it brings me the names? I tried with:
SELECT U.* FROM USERS U INNER JOIN NACIONALIDADES N ON U.NACIONALIDAD IN ( N.ID )
I expect such an output
ID | NOMBRE | NACIONALIDAD
1 | JUAN | Ruso,Español,Brasileño
2 | PEDRO | Ruso,Español
3 | JOSE | Ruso,Brasileño
I am using PHP, I could first get an initial array of nationalities and then compare the indexes, but I would like to know if there is a direct query with the database.
Thank you
We agree that it will be necessary to normalize your situation.
However your question seemed curious to me, so I tried a solution. In fact, what you want can be achieved using
FIND_IN_SET
.The query would be like this:
And the result:
Note that I have applied an
ORDER BY
insideGROUP_CONCAT
to give me the list of ordered nations. If you are interested in any order you can remove it.show
Here you can see a DEMO EN REXTESTER.
If it is
Mysql
, you can useYes it is
SQLServer
XML PATH
Postgres also has one