Question

I have a large Mysql database connected with a php platform.

I have few table with this structure:

Table USER:

id (int auto increment not null, primary key)
name (varchar 200)
spoken_lang (varchar 400) /* The value of this field is the id of the table languages, 
                             with the char ';' like a separator ;*/

Table LANGUAGES

id (int auto increment not null, primary key) /* Used also in the prev table */
name (varchar 200)

Is it possible to make a single search query that is be able to compare the column user.name, and also the table languages.name?

Something like this:

SELECT user.name, languages.name as lang 
FROM 
user JOIN languages ON user.spoken_lang = ......  
Was it helpful?

Solution

I would first have to recommend you normalize your table -- you shouldn't be storing a list of results in a single column. If possible, consider creating a User_Language table which stores the User_Id and the Language_Id.

However, you can achieve the same results using FIND_IN_SET and REPLACE:

select u.name, l.name language
from user u
  join languages l on find_in_set(l.id, replace(u.spoken_lang,';',','))

OTHER TIPS

You can do this using like as the join condition:

select u.name, l.name as lang
from user u join
     languages l
     on concat(';', u.spoken_lang, ';') like concat('%;', l.name, ';%')

The idea is to add the separator (';') to the beginning and end of each language. And then search for cases where the spoken language is like the language. For instance, if you have 'English;Spanish;Russian', then it will compare as:

';English;Spanish;Russian;' like '%;Russian;%'

And find a match. You don't have to worry about partial matches, because the semicolons delimit each language.

In MySQL, you can also do this with find_in_set(), but that requires replacing the semicolons with commas:

on find_in_set(l.lang, replace(u.spoken_lang, ';', ',')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top